Search code examples
node.jserror-handlingsendfile

How can I catch the errors in sendFile function?


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?


Solution

  • There are basically four choices here:

    1. You handle the error inside the callback, right in your if (err) { ... } block.
    2. You call a callback from inside the if (err) { ... } block and that callback can notify other code.
    3. You set up some sort of eventEmitter (like what a stream object uses) and you emit an error event on that object and the code that wants to see the error listens for the error event on that object.
    4. You use promises and reject a promise which the calling code can monitor.

    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.