Mastering JavaScript Error Handling: From Try‑Catch to Global onerror

This article explains why proper JavaScript error handling is essential, compares syntax and runtime errors, demonstrates good and bad try‑catch patterns, shows how to use global onerror listeners, capture stack traces, and handle asynchronous exceptions to improve frontend code reliability.

21CTO
21CTO
21CTO
Mastering JavaScript Error Handling: From Try‑Catch to Global onerror

JavaScript error handling is crucial for robust front‑end applications. Inspired by Murphy's law, the article starts by emphasizing that uncaught errors degrade user experience and that modern browsers expose raw error messages to users.

Unlike Java or C#, which provide built‑in exception mechanisms, JavaScript gained a similar try‑catch system starting with ES3, allowing developers to recover from runtime failures.

Errors in JavaScript fall into two categories:

Syntax errors – parsing failures that prevent code execution, such as missing brackets.

Runtime errors – exceptions thrown when an operation is illegal, e.g., calling an undefined method.

Example code demonstrates a function that triggers a TypeError and a corresponding Mocha test:

function error() {<br/>    var foo = {};<br/>    return foo.bar();<br/>}
it('throws a TypeError', function () {<br/>    should.throws(target, TypeError);<br/>});

A poorly designed handler ( badHandler) swallows errors and returns null, making debugging difficult:

function badHandler(fn) {<br/>    try {<br/>        return fn();<br/>    } catch (e) {<br/>    }<br/>    return null;<br/>}

A better approach ( uglyHandler) re‑throws a new error, preserving stack information for debugging:

function uglyHandler(fn) {<br/>    try {<br/>        return fn();<br/>    } catch (e) {<br/>        throw Error('a new error');<br/>    }<br/>}

For global error handling, the article recommends using the window.onerror or addEventListener('error') listener to capture any uncaught exception, log its stack trace, and optionally send it to a server:

if (window.addEventListener) {<br/>    window.addEventListener('error', function (e) {<br/>        var error = e.error;<br/>        console.log(error);<br/>    });<br/>} else if (window.attachEvent) {<br/>    window.attachEvent('onerror', function (e) {<br/>        var error = e.error;<br/>        console.log(error);<br/>    });<br/>} else {<br/>    window.onerror = function (e) {<br/>        var error = e.error;<br/>        console.log(error);<br/>    };<br/>}

Capturing the stack trace is valuable for pinpointing the source of errors. The article shows how to extract the stack from the error object and send it via an XMLHttpRequest:

window.addEventListener('error', function (e) {<br/>    var stack = e.error.stack;<br/>    var message = e.error.toString();<br/>    if (stack) {<br/>        message += '
' + stack;<br/>    }<br/>    var xhr = new XMLHttpRequest();<br/>    xhr.open('POST', '/log', true);<br/>    xhr.send(message);<br/>});

When dealing with asynchronous code, a plain try‑catch cannot catch errors thrown inside callbacks or promises. The article illustrates this limitation and suggests wrapping asynchronous calls or using global handlers:

function asyncHandler(fn) {<br/>    try {<br/>        setTimeout(function () {<br/>            fn();<br/>        }, 1);<br/>    } catch (e) { }<br/>}

Instead, place try‑catch inside the asynchronous callback or rely on the global onerror listener to capture such exceptions.

In conclusion, the article advocates avoiding silent failures; developers should surface errors, capture stack information, and use a combination of local try‑catch blocks and global error listeners to maintain clean, debuggable front‑end code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DebuggingfrontendAsynchronousError HandlingException
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.