rest-api-error-factory

0.1.2 • Public • Published

rest-api-error-factory

CircleCI Codecov npm npm license

A factory function to create REST API error classes.

Usage

const Koa = require('koa')
const Router = require('koa-router')
const restAPIErrorFactory = require('rest-api-error-factory')
 
const errors = {
  CLIENT_INVALID_PARAM: {
    message: 'Invalid parameter (%s).',
    httpStatus: 400
  },
 
  CLIENT_RESOURCE_NOT_FOUND: {
    message: 'Resouce not found.',
    httpStatus: 404
  },
 
  SERVER_INTERNAL_ERROR: {
    message: 'Server Internal Error (EVENT_ID: %s-%s).',
    httpStatus: 500
  }
}
 
// create a REST API error class
const RESTError = restAPIErrorFactory(errors)
 
const app = new Koa()
const router = new Router()
 
app.use(async(ctx, next) => {
  try {
    await next()
  } catch (e) {
    if (!(instanceof RESTError)) {
      // here we use raven-logger to log unexpected errors
      // https://github.com/kasha-io/raven-logger
      const { timestamp, eventId } = logger.error(e)
      e = new RESTError('SERVER_INTERNAL_ERROR', timestamp, eventId)
    }
 
    // here we reply the request with REST API message.
    ctx.status = e.httpStatus
    ctx.body = e.toJSON()
  }
})
 
router.get('/articles/:id', async ctx => {
  const id = parseInt(ctx.params.id)
  if (isNaN(id)) {
    // throw the error
    throw new RESTError('CLIENT_INVALID_PARAM', 'id', { id: ctx.params.id })
  }
 
  // ...
})
 
app.use(router)
 
app.use(ctx => {
  throw new RESTError('CLIENT_RESOURCE_NOT_FOUND')
})
 
app.listen(3000)

APIs

restAPIErrorFactory(errorDefs)

Creates an error class that contains error definitions you passed.

errorDefs format:

{
  ERROR_CODE: {
    message: 'MESSAGE'
    httpStatus: STATUS_CODE
  },
 
  ...
}

Example:

const RESTError = restAPIErrorFactory({
  CLIENT_INVALID_PARAM: {
    message: 'Invalid parameter (%s).',
    httpStatus: 400
  }
})

new RESTError(errorCode, [messageParam1, messageParam2, ...], [extraProperties])

Creates an error instance.

Params:

errorCode: String. The error code you defined in error definition object.
messageParams1, messageParam2, ...: String | Number. The params to format the error message. The message will be formatted by util.format(message, messageParam1, messageParam2, ...). See util.format for details.
extraProperties: Object. Extra properties to set.

Example:

const e = new RESTError('CLIENT_INVALID_PARAM', 'id', { id: 'foo' })
 
console.log(e.httpStatus)
// -> 400
 
console.log(e.toJSON())
/*
->
{
  code: 'CLIENT_INVALID_PARAM',
  message: 'Invalid parameter (id).'
  id: 'foo'
}
 
httpStatus will be excluded
*/

new RESTError(json)

Creates an error instance from JSON object.

Params:

json: JSON object. You can get it from restError.toJSON().

Example:

const e = new RESTError({
  code: 'CLIENT_INVALID_PARAM',
  message: 'Invalid parameter (id).',
  id: 'foo'
})

Package Sidebar

Install

npm i rest-api-error-factory

Weekly Downloads

2

Version

0.1.2

License

MIT

Unpacked Size

9.76 kB

Total Files

6

Last publish

Collaborators

  • jiangfengming