UNPKG

express-api-problem

Version:

A minimal package to assist in returning RESTful exceptions in your APIs

37 lines (36 loc) 1.43 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const http_status_codes_1 = require("http-status-codes"); const api_problem_1 = require("./api-problem"); exports.ExpressMiddleware = function (options = {}) { // Merge the options with defaults options = Object.assign({ stackTrace: true, contentType: 'application/problem+json' }, options); return function (err, req, res, next) { // For API problems, just respond with the error if (err instanceof api_problem_1.ApiProblem) { res .status(err.status) .header('Content-Type', options.contentType) .send(JSON.stringify(err)); return; } // For Exceptions, create internal error exception if (err instanceof Error) { const error = new api_problem_1.ApiProblem({ status: http_status_codes_1.INTERNAL_SERVER_ERROR, detail: err.message, additional: options.stackTrace ? { stack: (err === null || err === void 0 ? void 0 : err.stack) || undefined, } : undefined, }); res .status(error.status) .header('Content-Type', options.contentType) .send(JSON.stringify(error)); return; } next(); }; };