2022-03-02 12:50:15 +08:00
|
|
|
export class ErrorHandler {
|
|
|
|
handlers = [];
|
|
|
|
|
|
|
|
register(guard: (err) => boolean, render: (err, ctx) => void) {
|
|
|
|
this.handlers.push({
|
|
|
|
guard,
|
|
|
|
render,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
defaultHandler(err, ctx) {
|
|
|
|
ctx.status = err.statusCode || err.status || 500;
|
|
|
|
ctx.body = {
|
|
|
|
errors: [
|
|
|
|
{
|
|
|
|
message: err.message,
|
|
|
|
code: err.code,
|
|
|
|
},
|
|
|
|
],
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
middleware() {
|
|
|
|
const self = this;
|
|
|
|
|
|
|
|
return async function errorHandler(ctx, next) {
|
|
|
|
try {
|
|
|
|
await next();
|
|
|
|
} catch (err) {
|
2022-03-06 16:19:18 +08:00
|
|
|
console.error(err);
|
2022-03-02 12:50:15 +08:00
|
|
|
for (const handler of self.handlers) {
|
|
|
|
if (handler.guard(err)) {
|
|
|
|
return handler.render(err, ctx);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
self.defaultHandler(err, ctx);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|