Handling Errors In JavaScript – DEV Community

Error dealing with is a crucial a part of any code you write. For instance, if you’re growing a library for use by different builders, they do not wish to take care of errors that may crop up. These errors would both trigger the library to interrupt or would require additional effort on their half to resolve.
It is a good suggestion to plan for the way you’ll deal with errors earlier than writing your software program within the first place, however it’s much more vital to truly comply with by and deal with errors successfully as soon as the software program has been written. On this put up, we’ll look at a (contrived) hypothetical situation and have a look at ways in which we will deal with errors in JavaScript.



Error syntax

When an exception happens, the browser stops executing your script and shows an error message. The attempt…catch assertion catches and handles these exceptions in order that they do not trigger the browser to cease working your program.

Generally JavaScript error syntax is as proven under:

attempt {
  code block to  attempt
}
catch(err) {
   code to deal with the catched error
}
lastly {
  Block of code to be executed regardless of the attempt / catch result
}
Enter fullscreen mode

Exit fullscreen mode

The attempt block executes first and if an exception happens or throws in the course of the execution, the catch block is executed. The Lastly block is executed whether or not an exception is thrown or not.

If there isn’t any catch block in your program, then this system will terminate with an error message, each time there’s an error.



Utilizing the Error Object

The Error Object is a particular error handler that’s used to deal with runtime errors in JavaScript. This object permits you to establish the kind of error that occurred, in addition to its supply and different details about it.
The runtime error could be a logic error, undefine variable or features, or division by zero.

Contemplate the next situation: in the event you’re using an exterior script in your software program, you will want to make use of attempt to catch in your code to deal with any errors which will happen when the exterior script is up to date, as proven under.

attempt {
  username = doument.getElementById("username").worth
   password = doument.getElementById("password").worth
if(validate(username, password)== true){
  //login efficiently 
}else{
   // username/password not right 
}
} catch (e) {
  console.error(e.title + ': ' + e.message)
  alert("an error happen, we're working to repair it!!!")
}
Enter fullscreen mode

Exit fullscreen mode

If the perform validate within the exterior script is renamed or has an error, and it was not up to date in the principle script, it should generate a customized message for the consumer. As a substitute of throwing errors and terminating this system execution.

If the Validate() is been modified within the exterior script and you haven’t



Make the most of Error Occasions

Error Occasions is a perform that permits you to deal with errors which will happen when loading exterior HTML recordsdata in your program. It attaches a handler to the window object’s error occasion. That manner the script may be knowledgeable each time an exterior useful resource fails.
Error occasions are used for dealing with HTML components equivalent to img, video, audio, object, body, and so on when their useful resource fails to load. Every aspect will need to have onerror attribute, containing a perform to deal with the error, as demonstrated under.

<img src="picture.jpg" onerror="error_function()">
Enter fullscreen mode

Exit fullscreen mode

At any time when the picture.jpg fails to load, the perform contained in the onerror attribute will likely be triggered for us to deal with the error in our code as proven under:

perform error_function() {
  console.log("The picture couldn't be loaded.");
}
Enter fullscreen mode

Exit fullscreen mode

We will additionally use the HTML DOM to assign an onerror occasion to a component. let’s take as an example, a video aspect, if a video fails to load or its URL is invalid, we will show a customized message to the customers as proven under:

<!DOCTYPE html>
<html>
<physique>

<p>Dealing with javascript errors</p>

<img id="myImg" src="picture.png">

<span id="demo"></span>

<script>
doc.getElementById("myImg").onerror = perform() {error_function()};

perform error_function() {
  doc.getElementById("demo").innerHTML = "The picture couldn't be loaded.";
}
</script>

</physique>
</html>

Enter fullscreen mode

Exit fullscreen mode



Create Customized Errors

Javascript permits builders to throw an error exception if sure situations are usually not met or to throw an exception on a selected line.

You’ll be able to management your program circulation and generate customized error messages by utilizing throw state inside attempt assertion. This provides you the chance to outline your personal error sorts.

throw "error message"
Enter fullscreen mode

Exit fullscreen mode

When the execution reaches throw, the customized exception message is thrown. Contemplate an instance of use it.

perform myFunction() {
  const message = doc.getElementById("p01");
  message.innerHTML = "";
  let x = doc.getElementById("demo").worth;
  attempt {
    if(x == "") throw "empty";
    if(isNaN(x)) throw "not a quantity";
    x = Quantity(x);
    if(x < 5) throw "too low";
    if(x > 10) throw "too excessive";
  }
  catch(err) {
    message.innerHTML = "Enter is " + err;
  }
}

Enter fullscreen mode

Exit fullscreen mode

Add a Comment

Your email address will not be published. Required fields are marked *