简体   繁体   中英

JavaScript errors not showing up in console?

fields is undefined in the following code snipped, but it is not logged to the console when the error happens. In this specific instance, why, and what is the de facto way to handle this?

"Testing" is logged to the console (Line #2), but the undefined variable fields (Line #4) is not being reported. The error is returned in an API response (Line #5) but with no relevant information such as line #, stack trace, etc.

How can I make errors like this log to the console, and why are they not?

export function post(req, res) {
  console.log("Testing")
  User.create( getFields(req, ["name_first", "name_last"]) )
    .then(user =>  respondJSON (res, fields, { status: 201 }))
    .catch(err => respondError (res, err))
}

Since the catch is responding with an error, I get the following API response:

{
  "error": true,
  "data": {
    "message": "fields is not defined"
  }
}

I am using Babel 6 and babel-node to run my code through NPM scripts. I am using morgan logging as well. Removing the middleware for logging does not alter the error output.

The automatic logging to console is a mechanism for unhandled exceptions. Because Promises automatically catch exceptions in the callbacks, the exceptions are no-longer unhandled, so nothing will be automatically logged.

If you want it to be logged, you could perhaps add a throw err at the end of your catch block. This will convert it into an unhandled promise rejection, which is typically handled similarly to an unhandled exception.

Because you didn't actually log the error?

export function post(req, res) {
  console.log("Testing")
  User.create( getFields(req, ["name_first", "name_last"]) )
    .then(user =>  respondJSON (res, fields, { status: 201 }))
    .catch(err => {
      console.error(err);
      respondError(res, err);
    });
}

I had a similar problem caused by a 'finally' which was appended to the main async function running.

run()
.finally(()=>{process.exit(0)})

modifying it to:

run()
.catch(err => {console.log(err)})
.finally(()=>{process.exit(0)})

solved the problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM