Reputation: 1120
This may be extremely stupid, but I haven't found much about this because I don't understand how I should search this.
I have a route handler that may call different functions depending on some request parameters, and I would like to know what's the best way to deal with errors inside the functions in order to pass errors to the error handling middleware. Consider something like this:
router.get('/error/:error_id', (req, res, next) => {
my_function();
}
function my_function(){
// do something async, like readfile
var f = fs.readFile("blablabla", function (err, data) {
// would want to deal with the error
});
}
If an error occurs during fs.readFile
, how do I pass the error to next
to forward it to the error middleware? The only solution is to pass the next param to the function function my_function(next){...}
?
In case the function didn't call any async I/O operation, a simple try/catch
in the route handler would be ok (i suppose), like this:
router.get('/error/:error_id', (req, res, next) => {
try{
my_function();
} catch(e){
next(e);
};
}
function my_function(){
// do stuff
var f = fs.readFileSync("blablabla"); // possibly throws an error
}
Hope I make some sense.
Upvotes: 0
Views: 52
Reputation: 31
There are two types of errors can be occured in our server. So try catch block can handle Synchronous errors.
try {
my_function();
}
catch(e){
};
But for asynchronous errors
try {
my_function();
}
catch(e){
next(e);
};
also you chan use .then() instead of try catch
Promise.resolve().then(() => {
throw new Error('BROKEN')
}).catch(next)
documentation - Express error handling
you can use express-async-handler for handle this very easy express-async-handler
Upvotes: 0
Reputation: 600
You are totally correct that you should pass the next
callback to my_function
since fs.readFile
is asynchronous.
router.get('/error/:error_id', (req, res, next) => {
my_function(next);
}
function my_function(next) {
fs.readFile("blablabla", function (err, data) {
if (err) {
next(err);
} else {
// Process the data
// Don't forget to call `next` to send respond the client
}
});
}
By the way, you cannot do
var f = fs.readFile(...)
because fs.readFile
is asynchronous. The data should be handled within the callback.
Upvotes: 1