I want to write a common error handler which will catch custom errors thrown on purpose at any instance of the code.
When I did throw new Error('sample')
like in the following code
try {
throw new Error({'hehe':'haha'});
// throw new Error('hehe');
} catch(e) {
alert(e);
console.log(e);
}
Log shows in Firefox as Error: [object Object]
and I couldn’t parse the object.
For the second throw
the log shows as: Error: hehe
Whereas when I did
try {
throw ({'hehe':'haha'});
} catch(e) {
alert(e);
console.log(e);
}
the console showed as: Object { hehe="haha"}
in which I was able to access the error properties.
What is the difference?
Is the difference as seen in the code? Like string will be just passed as string and object as objects but the syntax will be different?
I haven’t explored throwing error object… I had done only throwing strings.
Is there any other way than the above two mentioned methods?
This question is related to
javascript
object
error-handling
exception-handling
throw
throw something
works with both object and strings.But it is less supported than the other method.throw new Error("")
Will only work with strings and turns objects into useless [Object obj] in the catch block.
You first mention this code:
throw new Error('sample')
and then in your first example you write:
throw new Error({'hehe':'haha'})
The first Error object would actually be useful, because it is expecting a string value, in this case 'sample'. The second would not because you are trying to pass an object in, and it is expecting a string, and would not display a helpful error.
The error object would have the "message" property, which would be 'sample'.
you can throw
as object
throw ({message: 'This Failed'})
then for example in your try/catch
try {
//
} catch(e) {
console.log(e); //{message: 'This Failed'}
console.log(e.message); //This Failed
}
or just throw a string error
throw ('Your error')
try {
//
} catch(e) {
console.log(e); //Your error
}
throw new Error //only accept a string
Apart from the rest of the answers, I would like to show one difference in React.
If I throw a new Error()
and I am in development mode, I will get an error screen and a console log. If I throw a string literal, I will only see it in the console and possibly miss it, if I am not watching the console log.
Throwing an error logs into the console and shows an error screen while in development mode (the screen won't be visible in production).
throw new Error("The application could not authenticate.");
Whereas the following code only logs into the console:
throw "The application could not authenticate.";
The following article perhaps goes into some more detail as to which is a better choice; throw 'An error'
or throw new Error('An error')
:
http://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/
It suggests that the latter (new Error()
) is more reliable, since browsers like Internet Explorer and Safari (unsure of versions) don't correctly report the message when using the former.
Doing so will cause an error to be thrown, but not all browsers respond the way you’d expect. Firefox, Opera, and Chrome each display an “uncaught exception” message and then include the message string. Safari and Internet Explorer simply throw an “uncaught exception” error and don’t provide the message string at all. Clearly, this is suboptimal from a debugging point of view.
TLDR: they are equivalent Error(x) === new Error(x)
.
// this:
const x = Error('I was created using a function call!');
????// has the same functionality as this:
const y = new Error('I was constructed via the "new" keyword!');
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
throw and throw Error will are functionally equivalent. But when you catch them and serialize them to console.log they are not serialized exactly the same way:
throw 'Parameter is not a number!';
throw new Error('Parameter is not a number!');
throw Error('Parameter is not a number!');
Console.log(e) of the above will produce 2 different results:
Parameter is not a number!
Error: Parameter is not a number!
Error: Parameter is not a number!
The Error
constructor is used to create an error object. Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions.
User-defined Errors are thrown via the throw
statement. program control will be passed to the first catch
block in the call stack.
The difference between throwing an error with and without Error object:
throw {'hehe':'haha'};
In chrome devtools looks like this:
Chrome tells us that we have an uncaught error which just is a JS object. The object itself could have information regarding the error but we still don't know immediately where it came from. Not very useful when we are working on our code and debugging it.
throw new Error({'hehe':'haha'});
In chrome devtools looks like this:
An error thrown with the Error object gives us a stack trace when we expand it. This gives us valuable information where the error precisely came from which is often valuable information when debugging your code. Further note that the error says [object Object]
, this is because the Error
constructor expects a message string as a first argument. When it receives a object it will coerce it into a string.
throw
will terminate the further execution & expose message string on catch the error.
try {
throw "I'm Evil"
console.log("You'll never reach to me", 123465)
} catch (e) {
console.log(e); // I'm Evil
}
_x000D_
Console after throw will never be reached cause of termination.
throw new Error
exposes an error event with two params name & message. It also terminate further execution
try {
throw new Error("I'm Evil")
console.log("You'll never reach to me", 123465)
} catch (e) {
console.log(e.name, e.message); // Error I'm Evil
}
_x000D_
And just for completeness, this works also, though is not technically the correct way to do it -
try {
throw Error("I'm Evil")
console.log("You'll never reach to me", 123465)
} catch (e) {
console.log(e.name, e.message); // Error I'm Evil
}
console.log(typeof(new Error("hello"))) // object
console.log(typeof(Error)) // function
_x000D_
Source: Stackoverflow.com