Skip to content

Using custom Error types for consistency and brevity in error status codes #5

@djfarrelly

Description

@djfarrelly

Copied from bufferapp/micro-rpc#2

Purpose

Inspired by Apollo server's way to throw errors, I was thinking it might be a little nicer than the current createError pattern.

Proposal

Instead of creating the error and optionally pass an error code, we have specific errors that consumers can import which might make things consistent.

const {
  rpc,
  method,
  ParameterError,  // or UserInputError like Apollo
  ForbiddenError,
  FatalError,
} = require('@bufferapp/micro-rpc');

module.exports = rpc(
  method('getUser', async ({ _id }) => {
    if (!accessToken || isValidAccessToken(accessToken)) {
      throw new ForbiddenError()
      // response => 403 { message: 'Forbidden' }
    }
    if (!_id) {
      throw new ParameterError(`_id required`)
      // response => 400 { message: '_id required' }
    }
    if (!isValidID(_id)) {
      throw new ParameterError('Invalid _id parameter')
      // response => 400 { message: 'Invalid _id parameter' }
    }
    try {
      const user = db.
    } catch (err) {
      throw new FatalError(`Database error finding user ${_id}`)
      // response => 500 { message: '_id required' }
    }
  })
)

These errors would already have the err.statusCode set.

This also could help us remove this library's dependency on micro or we could use this pattern to create a new micro-less rpc library since we're using Express under the hood.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions