2



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.

Amo
  • 333
  • 3
  • 12

1 Answers1

2

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.

Marian
  • 3,789
  • 2
  • 26
  • 36
  • Hey thanks for your answer, sadly my code is supposed to run in a lambda function of AWS so **process.on('unhandledRejection')** is not accessible in their environment (I didn't find an equivalent ) `axios.get('api_request', { 'auth': { 'bearer': 'Wrong_token' } }).then((res)=>{ console.log("RES HERE"); }).catch((error)=>{ console.log("ERROR FOUND"); throw error; })` I still get `ERROR FOUND (node:2508) UnhandledPromiseRejectionWarning: Error: Request failed with status code 401` which means that the catch is working so I don't get it haha – Amo Oct 19 '18 at 16:34
  • @Amo my idea was that you can choose to log the error without crashing by NOT throwing it in the catch handler. Sort of "hey, this failed, and I know that, and I'll log that, but my app doesn't care about this enough to crash". If you choose to throw, then no need to log the error an extra time. – Marian Oct 19 '18 at 16:48
  • @Amo also, `process.on('unhandledRejection')` works in aws lambda. You can set the listener in the file with your handler code. I believe, setting it outside the actual handler function works best, as we don't want to set multiple listeners for the same thing in a single process. So just somewhere at the top of the file above your handler and after your imports will do. – Marian Oct 19 '18 at 16:51
  • Ok so the point is that I'm using Lambda functions in AWS to load lots of data from an API. It needs a timeout long enough to allow the Lambda to load all the data. But if an error occur and I get this `UnhandledPromiseRejection`, the lambda is waiting for the timeout before stoping itself and I pay all the useless execution time ... That is why I want the lambda to crash immediately when an error occur and not just a log :/. – Amo Oct 19 '18 at 19:05
  • Now I tried `process.on('unhandledRejection')` outside the handler and It worked ( **Thank you ;)** ) But how could I do to get the right error and not `"errorMessage": "RequestId: 374cb64d-d3d1-11e8-99b9-9ddc5d4dec4e Process exited before completing request"` ? Thank you for your time ;) ! – Amo Oct 19 '18 at 19:05
  • @Amo is this message from logs? Or a response to an api call? – Marian Oct 19 '18 at 19:58
  • @Amo you could try [this question](https://stackoverflow.com/questions/31329495/is-there-a-way-to-change-the-http-status-codes-returned-by-amazon-api-gateway) for more details on changing error messages. If you need a more specific answer, it probably warrants another separate question, as we are definitely stirring away from the original topic. – Marian Oct 19 '18 at 20:02
  • It is the result returned by the lambda function. I will probably stay like this for now because I spent too much time on it for now ! Thank you for solving the main part of my problem ! – Amo Oct 20 '18 at 08:28