Reputation: 11678
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
}
Upvotes: 15
Views: 24049
Reputation: 1236
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
});
Upvotes: 16
Reputation: 346
this kind of try catch will not catch errors when some third function is called do the best solution will use global exception handler
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.end();
});
also you have to use promises in your end point handlers that will catch errors in any scope
Upvotes: 1
Reputation:
try catch
can not catch error asynchronously.
This will work:
app.get('/webhook', function (req, res) {
try {
//enter code here
} catch (error) {
// something here
}
});
But it is local and not the best way.
Good way is make error-handling middleware function. It is global. You need to define it after all app.use()
and routes calls.
app.use(function(err, req, res, next) {
// This is error handler
});
You can send the html page with details of error to client as usual.
Also, by default, Express have built-in error handler. The error will be written to the client with stack trace (It does not work in production mode).
Upvotes: 13