In one of my routes I want to send file with sendFile
function but I want to catch the errors may be occurred during send function. I wrote this code but the error which I throw not be caught by catch block and app crashes:
try {
res.sendFile(Path.join(__dirname, '../../uploads', fileName), null, (err) => {
if (err) {
throw err
}
})
} catch(err) {
Logger.error(err);
next(error);
}
How can catch this error?
There are basically four choices here:
if (err) { ... }
block.if (err) { ... }
block and that callback can notify other code.As you may have already found, the throw err
inside the callback does not do you any good. It just throws into the asynchronously called res.sendFile()
callback which is not something you can catch or monitor with your own code. The enclosing function here has already returned and the try/catch
you show will not catch the throw err
as that try/catch
scope is already done.
In your specific case, it seems like you can just do this:
res.sendFile(Path.join(__dirname, '../../uploads', fileName), (err) => {
if (err) {
Logger.error(err);
next(err);
}
});
Which is option 1) above.