You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
1.2 KiB
JavaScript

5 years ago
"use strict";
const defaultValue = require("default-value");
const http = require("http");
5 years ago
const chalk = require("chalk");
const util = require("util");
5 years ago
module.exports = function errorHandler(error, _req, res, _next) {
5 years ago
console.log(chalk.bold.red("Unhandled error:"), error.stack);
/* This extracts any (nested) metadata from chained errors */
let errorContext = (error.getAllContext != null)
? error.getAllContext()
: error;
console.log(chalk.red("Error metadata:"), util.inspect(errorContext, { colors: true, depth: 5 }));
let statusCode = (errorContext.isHttpError && errorContext.statusCode != null)
? errorContext.statusCode
5 years ago
: 500;
5 years ago
let errorCode = (errorContext.isHttpError && errorContext.errorCode != null)
? errorContext.errorCode
5 years ago
: "M_UNKNOWN";
5 years ago
let errorMessage = (errorContext.errorCode !== 500)
? defaultValue(errorContext.message, http.STATUS_CODES[statusCode])
5 years ago
: "An internal server error occurred. Please contact the server administrator for more information."
/* TODO: Add contact details? */
5 years ago
let errorMeta = (errorContext.errorMeta != null)
? errorContext.errorMeta
5 years ago
: {};
5 years ago
res.status(statusCode).json(Object.assign({}, errorMeta, {
5 years ago
errcode: errorCode,
error: errorMessage
}));
};