Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper non-string Javascript exceptions

Somehow this does not feel like the culmination of the 50 years programming language development:

  throw "My exception message here"; 

What's the correct way to do exceptions in Javascript, so that

  • They can be identified (instanceof)

  • They can carry other payload besides the default message and stack trace

  • They "subclass" base Exception, so that debug console and such can extract meaningful information about the exception

  • Possible nested exceptions (converting exception to another): if you need to catch an exception and rethrow new one the orignal stack trace would be preserved and could be meaningfully read by debugging tools

  • They follow Javascript best practices

like image 388
Mikko Ohtamaa Avatar asked Jan 29 '12 15:01

Mikko Ohtamaa


People also ask

What are JavaScript exceptions?

What is exception handling. Exception handling is one of the powerful JavaScript features to handle errors and maintain a regular JavaScript code/program flow. An exception is an object with an explanation of what went amiss. Also, it discovers where the problem occurred.

Can you throw anything in JavaScript?

You Can throw() Anything In JavaScript - And Other async/await Considerations.

Should you use exceptions in JavaScript?

For some people, throwing exceptions to indicate that there is no more values is a bad style; exceptions are made for exceptional behaviour. Moreover, exception handling is generally slower than simple tests. The difference is really minor (and maybe does not even exist) if the thrown instance is not created everytime.

How do you handle JavaScript errors?

JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally block, similar to other languages like Java or C#. try: wrap suspicious code that may throw an error in try block. catch: write code to do something in catch block when an error occurs.


1 Answers

throw new Error("message");

or if you want to be more specific use one of the Error Objects

It's important to make sure you throw real errors because they contain the stack trace. Throwing a string is stupid because it doesn't have any meta data attached to it.

You can also subclass errors

// for some sensible implementation of extend  // https://gist.github.com/1441105#file_1pd.js var MyError = extend(Object.create(Error.prototype), {    ... }); 
like image 95
Raynos Avatar answered Sep 22 '22 23:09

Raynos