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.

40 lines
1.3 KiB
JavaScript

"use strict";
const defaultValue = require("default-value");
const http = require("http");
const chalk = require("chalk");
const util = require("util");
module.exports = function errorHandler(error, _req, res, _next) {
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
: 500;
let errorCode = (errorContext.isHttpError && errorContext.errorCode != null)
? errorContext.errorCode
: "M_UNKNOWN";
let errorMessage = (statusCode !== 500)
? defaultValue(error.message, http.STATUS_CODES[statusCode])
: "An internal server error occurred. Please contact the server administrator for more information."
/* TODO: Add contact details? */
let errorMeta = (errorContext.errorMeta != null)
? errorContext.errorMeta
: {};
let errorCodeData = (!errorContext.noErrorCode)
? { errcode: errorCode, error: errorMessage }
: {};
res.status(statusCode).json(Object.assign({}, errorMeta, errorCodeData));
};