简体   繁体   中英

Is there a way in JavaScript to handle errors by the error name?

I am still learning JavaScript. I know Python too and in Python we can handle specific errors, for example to handle TypeErrors in Python, we could simply use except TypeError: and handle it. I want to know if there is a way in JavaScript to handle errors like,

Uncaught SyntaxError: Unexpected number

in this way. Thank you.

I'm not an javascript expert but I handled my errors so far like:

try {
  foo.bar();
} catch (e) {
  if (e instanceof ErrorType) {
    console.log(e.name + ': ' + e.message);
  }
  // ... etc
}

where ErrorType is a placeholder in my example.

Edit: As @VLAZ stated, this will only work for Runtime-Errors.

You can use try...catch method

 try { // your code } catch(err) { console.log(err.name) console.log(err.message); }

There are several types of error in JavaSript like: RangeError, ReferenceError, SyntaxError, TypeError, URIError So you can check for particular error type with err.name property like this

if (err.name === 'SyntaxError') {
            //handle that error type
        }

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