mount
mount copied to clipboard
Custom error thrown inside mounted app is converted to native Error
It's fairly common to throw objects inherited from Error, such as this:
class HttpError extends Error {
constructor(public status: number, message?: string) {
super(message);
this.name = 'HttpError';
Error.captureStackTrace(this, HttpError)
}
}
and then use middleware to capture and log these errrors and provide user friendly response:
const errorMiddleware = async (ctx, next) => {
try {
await next();
} catch (error) {
console.error(error);
if (error instanceof HttpError) {
ctx.status = error.status;
ctx.body = {
message: error.message,
};
return;
}
ctx.status = 500;
ctx.body = {
message: 'Internal server error',
};
}
};
Problem I'm facing is that thrown errors are "converted" back to Error and error instanceof HttpError
returns false. Is this expected behaviour? I'm throwing them like throw new HttpError(401, 'You are not logged in!');
do you have a failing test case?
Nope, it works in unit test: https://github.com/koajs/mount/pull/74 Maybe it's issue with koa-router, I'll report once I find the cause because we can still reproduce it in our project.