This repository has been archived on 2018-10-12. You can view files and clone it, but cannot push or open issues or pull requests.
ProgBlog/app/config/error-handlers.js

65 lines
1.5 KiB
JavaScript

'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');
const negotiate = require('express-negotiate');
let errorHandlers = new Set([
function handle404(req, res, next) {
if (! req.route) {
// if no route matches, send a 404
let err = new errors.Http404Error();
return next(err);
}
},
function handle400Errors(err, req, res, next) {
if (err instanceof negotiate.NotAcceptable) {
// if no content type matches, send a 406
err = new errors.Http406Error();
}
return next(err);
},
// 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;
}
// 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);
},
});
},
]);
module.exports = errorHandlers;