@getanthill/datastore
Version:
Event-Sourced Datastore
54 lines • 2.38 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.errorHandler = errorHandler;
const http_status_codes_1 = __importDefault(require("http-status-codes"));
function errorHandler(services) {
/**
* Note: the last argument `next` is important because if its not present, the function
* will not be called at all.
*/
return (err, _req, res, _next) => {
var _a;
if (typeof err !== 'object') {
// If the object is not an Error, create a representation that appears to be
err = {
name: 'Internal Server Error',
// eslint-disable-line no-param-reassign
status: http_status_codes_1.default.INTERNAL_SERVER_ERROR,
message: String(err), // Coerce to string
};
}
else {
// Ensure that err.message is enumerable (It is not by default)
Object.defineProperty(err, 'message', { enumerable: true });
Object.defineProperty(err, 'status', {
enumerable: true,
value: err.status || http_status_codes_1.default.INTERNAL_SERVER_ERROR,
});
}
if (err.status === http_status_codes_1.default.INTERNAL_SERVER_ERROR) {
services.telemetry.logger.error('[Express#ErrorHandler] Internal server error', err);
}
const errorBody = {
message: err.message,
status: err.status,
details: (_a = err.details) !== null && _a !== void 0 ? _a : [],
};
// If we have a server error, then we need to obfuscate its details in the
// response.
if (err.status === http_status_codes_1.default.INTERNAL_SERVER_ERROR) {
services.telemetry.logger.error('[Express#ErrorHandler] Internal Server Error', { err });
errorBody.message = 'Internal Server Error';
}
services.telemetry.logger.debug('[Express#ErrorHandler] Error response', {
errorBody,
});
res.locals.meter &&
res.locals.meter({ state: err.status, ...res.locals.attributes });
res.status(err.status).json(errorBody);
};
}
//# sourceMappingURL=errorHandler.js.map