Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom error thrown inside mounted app is converted to native Error #72

Open
DreadBoy opened this issue Mar 12, 2020 · 2 comments
Open

Comments

@DreadBoy
Copy link

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

@jonathanong
Copy link
Member

do you have a failing test case?

DreadBoy added a commit to DreadBoy/mount that referenced this issue May 6, 2020
@DreadBoy
Copy link
Author

DreadBoy commented May 6, 2020

Nope, it works in unit test:
#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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants