All files / backend/koa-middleware onError.js

100% Statements 6/6
100% Branches 8/8
100% Functions 1/1
100% Lines 6/6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 471x                                                                   5x 5x   5x 5x             1x  
const uuid = require('uuid/v4');
 
/**
 * @swagger
 * definition:
 *   InternalServerError:
 *     description:
 *       HTTP status code 500.
 *       Something got wrong in the flow and we have little idea what or why :)
 *
 *     properties:
 *       errorId:
 *         type: string
 *         format: uuid
 *
 *       errorCode:
 *         type: string
 *         example: INTERNAL_ERROR
 *
 *       errorMessage:
 *         type: string
 *         example: Page GET /api/v1/users failed
 */
 
/**
 * This middleware catches all thrown code error and
 * tries to return a proper error JSON response to the API call.
 *
 * @category middleware
 *
 * @param {Error} error The execution error that broke the script flow.
 * @param {Object} ctx Koa context
 */
function onError(error, ctx) {
  const errorId = error.id || uuid();
  ctx.logger.error(error.stack, {errorId});
 
  ctx.status = error.status || 500;
  ctx.body = {
    errorId,
    errorCode: error.code || 'INTERNAL_ERROR',
    errorMessage: error.message || `Page ${ctx.request.method} ${ctx.request.url} failed`,
  };
}
 
module.exports = onError;