Search code examples
javascriptnode.jserror-handlingaxioses6-promise

Axios request : promise error UnhandledPromiseRejectionWarning after catch anyway




I'm trying to manage errors properly in my code but I'm getting a warning like what I'm not handling the rejected promise, see below :

UnhandledPromiseRejectionWarning: Error: Request failed with status code 401
at createError (/Users/a/Documents/export/node_modules/axios/lib/core/createError.js:16:15)
at settle (/Users/a/Documents/export/node_modules/axios/lib/core/settle.js:18:12)
at IncomingMessage.handleStreamEnd (/Users/a/Documents/export/node_modules/axios/lib/adapters/http.js:201:11)
at IncomingMessage.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1092:12)
at process._tickCallback (internal/process/next_tick.js:63:19)

Here is my code :

const axios = require('axios');
axios.get('API_REQUEST', {
    'auth': {
        'bearer': 'NOT_WORKING_TOKEN' // To force the API to return an error ;)
    }
}).catch((error)=>{
    throw error;
})

For now I just want my program to crash without the warning when the error is throwing.


Solution

  • The catch block is typically used to recover from error. Any error thrown and not caught in a promise chain (inside the then, catch, etc.) will result in UnhandledPromiseRejection.

    If you are sure that this request failing does not introduce any undefined state into your app, you could just log the error and not throw.

    .catch(err => logger.error(err)) // or console.error()
    

    If you insist on crashing on a unhandled rejection, you could listen for that even globally, by putting the following code somewhere around the entry point of your app (like index.js)

    process.on('unhandledRejection', reason => {
        throw reason;
    });
    

    Also note, that future versions of Node are supposed to crash on unhandled promise rejections by default.