O'Reilly logo

Async JavaScript by Trevor Burnham

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, tracking down the causes of async errors isn’t ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required