How to Catch Errors in JavaScript

Part of being an efficient JavaScript programmer is not only ensuring your code runs the way you want it to, but also ensuring that you code your scripts to catch errors. It isn't always easy to catch JavaScript errors--especially when they're caused by outdated web browsers or by supplying incorrect data to a script. Fortunately, there's a little event you can include in your scripts to deal with scripting problems.

Things You'll Need

  • Web browser
  • JavaScript editor
Show More

Instructions

  1. Catch Errors in JavaScript

    • 1

      Introduce yourself to the onerror event. JavaScript's onerror event runs whenever a web browser encounters an error inside a running JavaScript. But it isn't effective all by itself. You need to tell the web browser what to do once the error occurs with a function.

    • 2

      Define the function first. Defining a function is a simple matter of telling a Web browser that a function exists, naming the functions and ending the functions.

    • 3

      Tell a web browser that a function exists with the word "function." Follow up with a unique name for the function, a pair of parentheses for parameters and then a left curly bracket. End the function with a right curly bracket on its own line. Example:
      function UhOh() {}

    • 4

      Replace "UhOh" with your own label definition.

    • 5

      Place in the commands that you want to run when the function " UhOh ()" is called later on in a script. Make sure these commands are their own lines between the left curly bracket and right curly bracket. You can put in a command to display such elements as an alert box, a confirmation box or a new web page.

    • 6

      Copy and paste into your own webpage the code below (beneath the code above):
      onerror = ErrorFound{
      UhOh()
      }
      In the above example, the JavaScript tells the browser to start a function named "ErrorFound," and to run the UhOh() function as a way to deal with any errors that it encounters.

    • 7

      Substitute the values in the above codes with your own after you have pasted them into your web page.

Tips & Warnings

  • Be sure to test your script in different browsers, as they don't all respond to JavaScript in the same way.

  • The onerror event does not catch all errors.

Related Searches:

Comments

You May Also Like

Related Ads

Featured