javascript - Calling async function in node.js -


i have async function

async function getpostasync() {   const post = await post.findbyid('id');    // if promise successful,   // post specific id doesn't exist   if (!post) {     throw new error('post not found');   }    return post; } 

i calling function with

app.get('/', (req, res) => {   getpostasync().then(post => {     res.json({       status: 'success',     });   }).catch(err => {     res.status(400).json({       status: 'error',       err     });   }) }); 

but receive

{   "status": "error",   "err": {} } 

i expect either error post not found or error connection or that, variable err empty object in catch statement.

consider following:

let e = error('foobar'); console.log( json.stringify(e) ) 

this outputs {}, in case. that's because errors don't serialize json well.

instead, try this:

res.status(400).json({   status : 'error',   err    : err.message // `string(err)` work }); 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -