@reflet/express
Version:
Well-defined and well-typed express decorators
58 lines (57 loc) • 1.87 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractErrorHandlers = exports.Catch = void 0;
const metadata_map_1 = require("./metadata-map");
const METAKEY_CATCH = Symbol('catch');
/**
* Attaches an error handler on a single route when applied to a method, or on multipe routes when applied to a router class.
* @see http://expressjs.com/en/guide/error-handling.html
*
* @remarks
* You can apply as many `Catch` decorators as you want.
* Error handlers are applied on the routes in the order they are written.
*
* @example
* ```ts
* @Catch(someDefaultErrorHandler)
* class Foo {
* @Catch((err, req, res, next) => {
* res.status(400).send(err.message)
* })
* @Get('/some')
* get(req: Request, res: Response, next: NextFunction) {
* throw Error('Nope')
* }
* }
* ```
* ------
* @public
*/
function Catch(errorHandler) {
return (target, key, descriptor) => {
// Method
if (key) {
const handlers = (0, metadata_map_1.getMetadata)(METAKEY_CATCH, target, key) || [];
handlers.unshift(errorHandler);
(0, metadata_map_1.defineMetadata)(METAKEY_CATCH, handlers, target, key);
}
// Class
else {
const handlers = (0, metadata_map_1.getMetadata)(METAKEY_CATCH, target.prototype) || [];
handlers.unshift(errorHandler);
(0, metadata_map_1.defineMetadata)(METAKEY_CATCH, handlers, target.prototype);
}
};
}
exports.Catch = Catch;
/**
* @internal
*/
function extractErrorHandlers(target, key) {
// Method
if (key)
return (0, metadata_map_1.getOwnMetadata)(METAKEY_CATCH, target.prototype, key) || [];
// Class
return (0, metadata_map_1.getOwnMetadata)(METAKEY_CATCH, target.prototype) || [];
}
exports.extractErrorHandlers = extractErrorHandlers;