Handling Async Errors

Like many modern languages, JavaScript allows you to throw exceptions and catch them in a try/catch block. If uncaught, most environments will give you a helpful stack trace. For example, this code will throw an exception because ’{’ is invalid JSON:

EventModel/stackTrace.js
​ 
​function​ JSONToObject(jsonStr) {
​ 
​return​ JSON.parse(jsonStr);
​ 
}
​ 
​var​ obj = JSONToObject(​'{'​);
​<= 
SyntaxError: Unexpected end of input
​ 
at Object.parse (native)
​ 
at JSONToObject (/AsyncJS/stackTrace.js:2:15)
​ 
at Object.<anonymous> (/AsyncJS/stackTrace.js:4:11)

The stack trace tells us not only where the error was thrown from but also where the original mistake was made: line 4. Unfortunately, ...

Get Async JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.