mount icon indicating copy to clipboard operation
mount copied to clipboard

Custom error thrown inside mounted app is converted to native Error

Open DreadBoy opened this issue 4 years ago • 2 comments

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!');

DreadBoy avatar Mar 12 '20 18:03 DreadBoy

do you have a failing test case?

jonathanong avatar Apr 28 '20 04:04 jonathanong

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.

DreadBoy avatar May 06 '20 13:05 DreadBoy