How to handle an Error correctly using Javascript?
when i want to send and Error using Javascript i do:
throw new Error()
it works, but if i pass a number, example:
throw new Error(500)
Th开发者_如何学Goe result is:
Error: 500
Where 'Error: ' is a string.
I have a function that handle this errors, this function must to know the code of the error, how to retrieve it? Do i have to parse the string? :-(
Thank you.
If you throw an error that way, the text between parenthesis becomes the error message. You can also throw using a custom Error Object.
A very useful link: The art of throwing JavaScript errors
Error instances have a message
property, and that's what you should analyze, not what it prints into console (which is Error.prototype.toString
).
See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error - the error message is always a string. Even if you pass a number to it, it will be implicitly converted to a string.
Error: 500
is the default string representation of an Error
object - that's what you get if you convert this object to a string or call error.toString()
directly. If you are interested in the error message you should access the message directly - parseInt(error.message, 10)
should do.
I highly recommend against throwing errors. Try catch is expensive and one slip up will mean your server shuts down.
I recommend you use the event approach, include eventemitters is most of your code.
That way you can just do this.emit("error", new Error(500))
If I get what you're saying, extract the number using some RegExp?
You don't actually need to use the Error object. You can just write throw
followed by whatever you want to be caught by a catch block.
This little code snippet displays 500 in the alert box.
function throwError(msg){
throw msg;
}
try{
throwError(500);
}catch(e){
alert(e);
}
If you test e
with typeof
it returns number.
精彩评论