All files / server/plugins/final index.js

68% Statements 17/25
56.25% Branches 9/16
100% Functions 2/2
71.43% Lines 15/21
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 47 48 49 50 51 52      11x   11x 11x     11x 89x 89x                           11x 7x 7x 7x   7x 7x     7x 7x             11x                  
// This file makes sure to clean up things in case there was something missing
// There are two reasons normally for this to happen: no reply was set or an
// unhandled error was thrown
const FinalError = require('./errors');
 
const { error } = require('../../router');
const { status } = require('../../reply');
 
// Make sure that a (404) reply is sent if there was no user reply
const statusHandler = async ctx => {
  Iif (!ctx.res) return;
  Eif (ctx.res.headersSent) return;
 
  // Send the user-set status
  if (ctx.res.explicitStatus) {
    return status(ctx.res.statusCode).send();
  }
 
  // Show it only if there was no status set in a return
  const err = new FinalError('noreturn', { status: 404, path: ctx.path });
  ctx.log.error(err.message);
  return status(404).send();
};
 
// Make sure there is a (500) reply if there was an unhandled error thrown
const errorHandler = ctx => {
  const error = ctx.error;
  ctx.log.error(error);
  Iif (ctx.res.headersSent) return;
 
  let status = error.status || error.code;
  Eif (typeof status !== 'number') status = 500;
 
  // Display the error message if this error is marked as public or not in production
  Eif (error.public || ctx.options.env !== 'production') {
    return ctx.res.status(status).send(error.message);
  }
 
  // Otherwise just display the default error for that code
  ctx.res.status(status).send();
};
 
module.exports = {
  name: 'final',
  // after: handler,
  after: [
    statusHandler,
    error(errorHandler)
  ]
};
// module.exports = handler;