2016-02-19 12:58:16 -05:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
// -----------------------------------------------------------------------------
|
|
|
|
// Error handlers
|
|
|
|
// -----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
const container = require('../Container');
|
|
|
|
const app = container.get('app');
|
|
|
|
const HTTP_CODE_MAP = require('http').STATUS_CODES;
|
|
|
|
const errors = require('errors');
|
2016-02-19 16:23:00 -05:00
|
|
|
const negotiate = require('express-negotiate');
|
2016-02-19 12:58:16 -05:00
|
|
|
|
|
|
|
let errorHandlers = new Set([
|
|
|
|
|
2016-02-19 16:23:00 -05:00
|
|
|
function handle400Errors(err, req, res, next) {
|
|
|
|
|
2016-02-19 12:58:16 -05:00
|
|
|
if (! req.route) {
|
2016-02-19 16:23:00 -05:00
|
|
|
// if no route matches, send a 404
|
|
|
|
err = new errors.Http404Error();
|
|
|
|
} else if (err instanceof negotiate.NotAcceptable) {
|
|
|
|
// if no content type matches, send a 406
|
|
|
|
err = new errors.Http406Error();
|
2016-02-19 12:58:16 -05:00
|
|
|
}
|
2016-02-19 16:23:00 -05:00
|
|
|
|
|
|
|
return next(err);
|
2016-02-19 12:58:16 -05:00
|
|
|
},
|
|
|
|
|
|
|
|
// general error handler
|
|
|
|
function handleError(err, req, res, next) {
|
|
|
|
let httpStatus = err.status || 500;
|
|
|
|
let message = err.message || HTTP_CODE_MAP[httpStatus];
|
|
|
|
|
|
|
|
res.status(httpStatus);
|
|
|
|
|
|
|
|
let output = {
|
|
|
|
status: httpStatus,
|
|
|
|
message: message,
|
|
|
|
};
|
|
|
|
|
|
|
|
// Show stack trace in development environment
|
|
|
|
if (app.get('env') === 'development') {
|
|
|
|
output.error = err;
|
|
|
|
}
|
|
|
|
|
2016-02-19 16:23:00 -05:00
|
|
|
// Send html or json depending on client accept header
|
|
|
|
req.negotiate({
|
|
|
|
html: () => {
|
|
|
|
res.render('error', {
|
|
|
|
title: `${err.status} ${err.message}`,
|
|
|
|
error: output,
|
|
|
|
});
|
|
|
|
},
|
|
|
|
|
|
|
|
'application/json': () => {
|
|
|
|
res.json(output);
|
|
|
|
},
|
2016-02-19 16:17:59 -05:00
|
|
|
});
|
2016-02-19 12:58:16 -05:00
|
|
|
},
|
|
|
|
]);
|
|
|
|
|
|
|
|
module.exports = errorHandlers;
|