Home > database >  Try catch block doesn`t catch error in node.js
Try catch block doesn`t catch error in node.js

Time:04-13

class AuthController {
    static methods = {
        GET: {
            '/auth/signup': {
                func: AuthService.signUp,
                response: (data, res) => {
                    res.statusCode = 200;
                    res.end(JSON.stringify(data));
                },
            },
        },
    };

    static use(req, res) {
        const route = this.methods[req.method][req.url];
        if (!route) {
            res.statusCode = 404;
            res.end(JSON.stringify({ message: 'Not found 404!' }));
            return;
        }
        try {
            const data = JSON.parse(req?.body?.data || '{}');
            const result = route.func({ ...data });
            route.response(result, res);
        } catch (err) {
            console.log(err, 'here');
            res.statusCode = err.statusCode || 500;
            res.end(JSON.stringify(err.message));
        }
    }
}


class AuthService {
    static async signUp({ login, password }) {
        if (!login || !password) throw new BaseError(400, 'kl', 'Custom error');
     }
}
   

It shows the error in console but try catch block doesn't see it. Here is the traceback. I don't know what the reason is because the function which throws error is inside of the block. Help please!

CodePudding user response:

I see one issue. You have declared signUp() to be async. That means it always returns a promise and it means that any throw operations inside it reject that promise that it returns (the exception doesn't propagate synchronously). But, when you attempt to call it here:

 const result = route.func({ ...data });

You don't await it so when signUp() rejects, the promise goes into result, but nobody ever handles the fact that the promise rejected and you get UnhandlePromiseRejectionWarning from the system.

I can't see the whole overall design (of all the other routes), but perhaps you just need to add await to this:

 const result = await route.func({ ...data });

And, you would have to make .use() be async also.


Or, if signUp() doesn't actually need to be async, then just remove the async from its declaration and the throw will be synchronous (instead of being turned into a rejected promise) and your try/catch will catch it then.

CodePudding user response:

The trace back that you attached tells you exactly what the problem is and what you need to do:

This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()

You can't catch an exception thrown by an async function with a try..catch block outside of that function, because script execution reaches the catch block before the async execution is finished. You therefor have to use .catch(..) instead:

const result = route.func({ ...data }).catch((err) => {
    console.log("catched error: ", err);
});

  • Related