@wthek/express-middleware
Version:
Express middleware for handling and formatting errors using http-error-kit. Ensures structured error responses with correct status codes.
38 lines (37 loc) • 1.61 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.KitExpressMiddleware = KitExpressMiddleware;
var http_error_kit_1 = require("http-error-kit");
var http_response_status_code_1 = require("http-response-status-code");
/**
* KitExpressMiddleware is a middleware for Express.js to handle errors in a standard
* and customizable way. The middleware will inspect the error and if it is an instance
* of KitHttpError or KitGeneralError, it will use the error's details to construct a
* response with the appropriate status code. If the error is not an instance of KitHttpError
* or KitGeneralError, the middleware will call the next function to propagate the error.
*
* @param {unknown} error The error to be handled.
* @param {Request} req The Express.js request object.
* @param {Response} res The Express.js response object.
* @param {NextFunction} next The Express.js next function.
*/
function KitExpressMiddleware() {
return function (error, req, res, next) {
var _a;
try {
if (error instanceof http_error_kit_1.KitHttpError ||
error instanceof http_error_kit_1.KitGeneralError) {
// eslint-disable-next-line
var statusCode = (((_a = error.getInputs()) === null || _a === void 0 ? void 0 : _a.statusCode) ||
http_response_status_code_1.INTERNAL_SERVER_ERROR);
res.status(statusCode).send(error);
}
else {
next(error);
}
}
catch (err) {
next(err);
}
};
}