Javascript Error Handling

JS Code Snippets Error Handling
Share:

About

In this code snippet, we’ll learn how to handle errors in Javascript.

You can throw errors by using the throw keyword. Then you can catch them using the try catch block. If you want to catch errors globally you can use the window.onerror event to call your error handling function.

Let’s see the code example below.

Code:

//Handle errors locally with try catch///////////////////

try{
//You execute your code here. console.log(addNumbers("5", 5)); }catch(ex){ //Here you would handle/log the error. I will just log it to the console, console.log(ex); }finally{ //Code here always executes. Regardless if an error was thrown or not. } function addNumbers(num1, num2){ //Check if input parameters aren't numbers throw an error. if(typeof num1 != "number") throw "num1 needs to be a number!"; if(typeof num2 != "number") throw "num2 needs to be a number!"; return num1 + num2; } //////////////////////////////////////////////////////// console.log("-----------------------------------------"); //Handle global errors////////////////////////////////// //If this function is called our global error handler will become active on the page. handleGlobalerrors(); //Lets try to change a constant and see how the error gets handled. const myVariable = 8; myVariable++; function handleGlobalerrors(){ window.onerror = function(msg, url, line, col, error){ let extra = !col ? '' : '\ncolumn: ' + col; extra += !error ? '' : '\nerror: ' + error; const message = "Error caught globaly: " + msg + "\nurl: " + url + "\nline: " + line + extra; //You would do some error login here. I will just display the error message to the console. console.log(message); //If true is returned then errors will be suppressed. return true; }; } ////////////////////////////////////////////////////////

Resulting output:

Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger