Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express.js global try/catch

I'm developing a rest server on Node JS with Express.

I'm trying to wrap all my endpoints in try\catch block, so a central point of error will response back to the sender with details. My problem that response (res instance) is alive for each of the endpoints methods, but I don't know how to make it global.

try {
    app.get('/webhook', function (req, res) {
        webhook.register(req, res);
    });

    app.get('/send', function (req, res) {
        sendAutoMessage('1004426036330995');
    });

    app.post('/webhook/subscribe', function (req, res) {
        webhook.subscribe("test");
    });

    app.post('/webhook/unsubscribe', function (req, res) {
        webhook.unsubscribe("test");
    });
} catch (error) {
    //response to user with 403 error and details
}
like image 727
Asaf Nevo Avatar asked Jul 05 '16 11:07

Asaf Nevo


People also ask

How do you handle errors in Express JS?

The simplest way of handling errors in Express applications is by putting the error handling logic in the individual route handler functions. We can either check for specific error conditions or use a try-catch block for intercepting the error condition before invoking the logic for handling the error.

How do I catch error in middleware Express?

For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next() function, where Express will catch and process them. For example: app. get('/', function (req, res, next) { fs.

Is it good to use try catch in node JS?

Note : It is a good practice to use Node. js Try Catch only for synchronous operations. We shall also learn in this tutorial as to why Try Catch should not be used for asynchronous operations.


1 Answers

There is a library (express-async-errors) which could suit your needs. This enables you to write async route handlers without wrapping the statements in try/catch blocks and catch them with global error handler. To make this work you must:
1. Install the express-async-errors package
2. Import package (before the routes)
3. Set up global express error handler
4. Write async route handlers (More info about this)

Example usage:

import express from 'express';
import 'express-async-errors';

const app = express();

// route handlers must be async
app.get('/webhook', async (req, res) => {
    webhook.register(req, res);
});

app.get('/send', async (req, res) => {
    sendAutoMessage('1004426036330995');
});

app.post('/webhook/subscribe', async (req, res) => {
    webhook.subscribe("test");
});

app.post('/webhook/unsubscribe', async (req, res) => {
    webhook.unsubscribe("test");
});

// Global error handler - route handlers/middlewares which throw end up here
app.use((err, req, res, next) => {
    // response to user with 403 error and details
});

like image 127
xab Avatar answered Oct 18 '22 19:10

xab