[javascript] UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

I am getting following error in my Node-Express App

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)

To say the least, I have created a helper function which looks something like this

const getEmails = (userID, targettedEndpoint, headerAccessToken) => {
    return axios.get(base_url + userID + targettedEndpoint,  { headers: {"Authorization" : `Bearer ${headerAccessToken}`} })
    .catch(error => { throw error})
}

and then I am importing this helper function

const gmaiLHelper = require("./../helper/gmail_helper")

and calling it inside my api route like this

router.get("/emailfetch", authCheck, async (req, res) => {
  //listing messages in users mailbox 
  let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
  .catch(error => { throw error})
  emailFetch = emailFetch.data
  res.send(emailFetch)
})

From my end, I think I am handling the error by using catch block.

Question: Can someone explain me why I am getting the error and how can I fix it?

This question is related to javascript node.js express

The answer is


.catch(error => { throw error}) is a no-op. It results in unhandled rejection in route handler.

As explained in this answer, Express doesn't support promises, all rejections should be handled manually:

router.get("/emailfetch", authCheck, async (req, res, next) => {
  try {
  //listing messages in users mailbox 
    let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
    emailFetch = emailFetch.data
    res.send(emailFetch)
  } catch (err) {
    next(err);
  }
})

I suggest removing the below code from getMails

 .catch(error => { throw error})

In your main function you should put await and related code in Try block and also add one catch block where you failure code.


you function gmaiLHelper.getEmails should return a promise which has reject and resolve in it.

Now while calling and using await put that in try catch block(remove the .catch) as below.

router.get("/emailfetch", authCheck, async (req, res) => {
  //listing messages in users mailbox 
try{
  let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
}
catch (error) { 
 // your catch block code goes here
})

You are catching the error but then you are re throwing it. You should try and handle it more gracefully, otherwise your user is going to see 500, internal server, errors.

You may want to send back a response telling the user what went wrong as well as logging the error on your server.

I am not sure exactly what errors the request might return, you may want to return something like.

router.get("/emailfetch", authCheck, async (req, res) => {
  try {
    let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
      emailFetch = emailFetch.data
      res.send(emailFetch)
   } catch(error) {
      res.status(error.response.status)
      return res.send(error.message);
    })

})

This code will need to be adapted to match the errors that you get from the axios call.

I have also converted the code to use the try and catch syntax since you are already using async.


I resolve the problem. It's very simple . if do you checking care the problem may be because the auxiliar variable has whitespace. Why ? I don't know but yus must use the trim() method and will resolve the problem


Questions with javascript tag:

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax Drag and drop menuitems Is it possible to execute multiple _addItem calls asynchronously using Google Analytics? DevTools failed to load SourceMap: Could not load content for chrome-extension TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app What does 'x packages are looking for funding' mean when running `npm install`? SyntaxError: Cannot use import statement outside a module SameSite warning Chrome 77 "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 Why powershell does not run Angular commands? Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop Push method in React Hooks (useState)? JS file gets a net::ERR_ABORTED 404 (Not Found) React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block Can I set state inside a useEffect hook internal/modules/cjs/loader.js:582 throw err How to post query parameters with Axios? How to use componentWillMount() in React Hooks? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once Objects are not valid as a React child. If you meant to render a collection of children, use an array instead How to reload current page? Center content vertically on Vuetify Getting all documents from one collection in Firestore ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How can I add raw data body to an axios request? Sort Array of object by object field in Angular 6 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Axios Delete request with body and headers? Enable CORS in fetch api Vue.js get selected option on @change Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) Angular 6: How to set response type as text while making http call

Questions with node.js tag:

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean` jwt check if token expired Using Environment Variables with Vue.js Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true Can not find module “@angular-devkit/build-angular” MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client npx command not found await is only valid in async function What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that? How to set bot's status Returning data from Axios API Error: EACCES: permission denied, access '/usr/local/lib/node_modules' ReferenceError: fetch is not defined ERROR in Cannot find module 'node-sass' Test process.env with Jest 'react-scripts' is not recognized as an internal or external command NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0' db.collection is not a function when using MongoClient v3.0 When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0) E: Unable to locate package npm How can the default node version be set using NVM? How to downgrade Node version How to solve npm install throwing fsevents warning on non-MAC OS? How to read file with async/await properly? Angular: Cannot Get / The difference between "require(x)" and "import x" Is there a way to force npm to generate package-lock.json? Angular - ng: command not found MongoError: connect ECONNREFUSED 127.0.0.1:27017 How can I use async/await at the top level? ERROR in ./node_modules/css-loader? Downgrade npm to an older version Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51 npm install Error: rollbackFailedOptional npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY How can I use an ES6 import in Node.js? Node.js: Python not found exception due to node-sass and node-gyp bash: npm: command not found? npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json' Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

Questions with express tag:

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js sequelize findAll sort order in nodejs Typescript import/as vs import/require? nodemon not working: -bash: nodemon: command not found Push items into mongo array via mongoose NodeJS accessing file with relative path Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response How to send a POST request from node.js Express? Start script missing error when running npm start How to provide a mysql database connection in single file in nodejs What is the difference between res.end() and res.send()? SyntaxError: expected expression, got '<' Understanding passport serialize deserialize TypeError: Router.use() requires middleware function but got a Object pass JSON to HTTP POST Request Purpose of installing Twitter Bootstrap through npm? Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused Proper way to set response status and JSON content in a REST API made with nodejs and express res.sendFile absolute path Sending JWT token in the headers with Postman How can I include css files using node, express, and ejs? req.body empty on posts POST request not allowed - 405 Not Allowed - nginx, even with headers included bodyParser is deprecated express 4 How to modify the nodejs request default timeout time? How can I set response header on express.js assets Node/Express file upload Basic HTTP authentication with Node and Express 4 Error: No default engine was specified and no extension was provided How to use Morgan logger? How to call a Python function from Node.js Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port How to generate unique ID with node.js Error: getaddrinfo ENOTFOUND in nodejs for get call File uploading with Express 4.0: req.files undefined What does "res.render" do, and what does the html file look like? Express.js Response Timeout Failed to load c++ bson extension create a trusted self-signed SSL cert for localhost (for use with Express/Node) Cannot GET / Nodejs Error ENOENT, no such file or directory