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
}
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.
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.
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With