Different Methods of Error Handling in jQuery

Errors are part and parcel for code. That being said, they can certainly result in a very bad user experience, especially if errors are not handled properly. Every code becomes perfect or bug free after a couple rounds of testing and fixing errors. Client side errors are difficult to handle, as most of the time they don’t occur at the time of compilation and instead rear their ugly heads at runtime only. The big problem with client side errors is that they are silently blocked. Client side errors are either displayed in the browser status bar or in the browser console, which makes them difficult to report. In this post we’ll look at different methods of handling errors in jQuery.

Types of Errors

Basically, there is no categorization when it comes to the types of errors, but some potential errors include syntax errors, coding errors, typos, incorrect business logic or incorrect input. The worst part about errors is that further execution of the code is halted and an error message is displayed. This will always throw a wrench in your plans, so let’s look at ways of handling it!

Using Try Catch

We all know jQuery is a library written on top of JavaScript. So traditional JavaScript techniques or functions are available within jQuery also. As a developer, you must be familiar with ‘try/catch’ and ‘finally’, which can both help you easily detect and handle errors.  All you need to do is put your error prone code inside a try block and catch block will catch the error. The syntax is quite simple.

Continue Reading Below
try {
  // Your code goes here…
catch(err) {
 // Handle the error here.

Along with ‘try/catch’, there is also a ‘finally’ block. The finally statement lets you execute code, after try/catch, regardless of the result. In other words, it’s always executed.

try {   // Your code goes here… }
catch(err) { // Handle the error here. }
finally { // Code always executed regardless of the result.

The try block must be followed by either exactly one catch block or one finally block (or one of each). When an error occurs in the try block, the error is placed in err (argument passed in the catch block) and the catch block is executed. The finally block executes unconditionally after try/catch.

Let’s look at an example:

Here, we will try to reference two undefined variables. So when the code reaches to that line, an error is thrown and the call goes directly to the catch block. The catch block will catch the error and then display it in a DOM element with id “error”:

try {
 var iResult = j/k; // Undefined variables will cause an error.
catch(e) {
   $('#error').val(Error Name: ' + e.name + ' Error Message: ' + e.message);

Remember, the catch block will get executed only when there is an error thrown by the try block. The error object passed into the catch block has 2 properties: name and message. The name property holds the error type, while the message property holds the actual error message. Please read this link for more details about the error object.

Normally, we don’t have any control on the error message displayed by the JavaScript as its part of the Error object. However, it’s always nice to have your own custom error messages rather than the standard error message, and there is actually a way to do this. Along with the try/catch blocks, there is also another option: the throw statement. The throw statement allows you to create a custom error. It is like throwing an error, which the catch block catches and handles, like so:

try {
  var iVal = $('#txtVal').val();
  if (iVal == '') throw "Value is empty.";
  if ($.isNumeric(iVal) == false) throw "Not a number";
catch(e) {

When throw is used, then the error object will contain the custom message only and it will log the same.

Using window.onError

“Window.onerror” acts like a global try/catch block which means that it can catch an error from anywhere in the code. It’s indeed one of the easiest ways to log client-side errors and report them to your server. When there is an uncaught exception or compile-time error, the window.onerror event handler is called with information about the error. The syntax is as follows:

window.onerror = function (message, source, lineno, columnNo, error) {
    // perform error handling here with file name and line number
    // for later processing
    return true; // The exception is handled, don't show to the user.

Here is a list outlining the descriptions of arguments passed to onerror:

  • Message – The message associated with the error, e.g. “Uncaught ReferenceError: j is not defined”
  • Source – The source of the script or document where the error was generated. 
  • LineNo – The line number where the error is found.
  • ColumnNo – The column number.
  • Error – The error object associated with this error.

Here’s an example to make this concept a little easier to understand:

function func1() {
 var iResult = j/k; // Undefined variables will cause an error.
window.onerror = function (message, source, lineno) {
  console.log("Error: " + message + " at line " + lineno + " in " + source);

The above code will log the error to the console with all the information. This function can be customized and server side logging can be done via making Ajax calls and passing the error objects.


If you are using the latest version of jQuery (3.1), then you can take advantage of the newly introduced handler called jQuery.readyException() which handles the errors thrown synchronously in functions wrapped in $.jQuery.

From jQuery documentation,

“This method is fired when an error is thrown synchronously in a function wrapped in jQuery() or jQuery( document ).ready(), or equivalent. By default it re-throws the error in a timeout so that it’s logged in the console and passed to window.onerror instead of being swallowed. Overwrite this method if you want to handle such errors differently.”

Let’s look at another example.

The following jQuery code tries to call a method named “doSomething()” on an object which is null:

$(document).ready(function() {
  var obj = null;
jQuery.readyException = function(error) {

When the error occurs, it reaches to the readyException handler which simply logs the error to the console. Here you can add code to perform server side logging or writing to a file.


Regardless of the nature of the client-side error, it is essential that all errors be handled swiftly. Here we learned a few different methods for handling errors, including: try/catch or windows.onerror, or the newly introduced jQuery.readyException handler (available with jQuery 3.1.0). You can customize the error handling based on your needs for server side logging, simply logging it to the console or writing to a file.

Leave a Comment


  • If you wish to post code examples, please wrap them in <code> tags.
  • Multi-line code should be wrapped in <pre><code> </code></pre>
  • Use &lt; instead of < and &gt; instead of > in the examples themselves. Otherwise, you could lose part of the comment when it's submitted.