1

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)

The 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.

1
  • Does your question refer to Javascript in general or specifically to javascript running on ther server with node.js? If specifically about node.js, then I understand Raynos's answer below. Otherwise, I can't see why making a slip with a try/catch block would shut down the server. One the client side, I find throwing errors and catching them in try/catch blocks indispensable. Commented Jun 11, 2012 at 10:03

6 Answers 6

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

Error instances have a message property, and that's what you should analyze, not what it prints into console (which is Error.prototype.toString).

Comments

1

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.

Comments

1

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))

Comments

0

If I get what you're saying, extract the number using some RegExp?

1 Comment

Please see my answer above. It shows you can pass a number directly to throw and catch it as a number in the catch block
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.