Error Handling in JavaScript

If you are a programmer and when you run code successfully, sometimes it’s a big surprise for you that “no error!!” why?? So, an error is a very common matter.

Bugs in code
Bug in Code

Error Types

There are three types of error :

  1. Syntax Error: It occurs when a programmer makes a mistake in a pre-defined programming language.
  2. Runtime Error: when a program executes, it may occur. The codes create runtime error is called exceptions.
  3. Logical Error: When there is any logical mistake in code, then it’s called logical error.

Today, I’ll discuss on runtime error like unexpected user input, erroneous server response, the program tried to open a non-existent file etc. Let’s Start.

“try-catch” Syntax

There is a syntax called try…catch that allows you to catch error in your code easily. It has three blocks like try, catch. If there is no error in the try block, then it ignores the catch block. But, if there is an error, then catch block give you error information.

try
{
// code that occurs error
}
catch(error)
{
// give error information
}

“try…catch” for only runtime error

The code must be runnable. In other words, it should be valid JavaScript. Otherwise, try…catch does not work. Like if there is any syntactically, then it does not work.

try {   { 
//code
} catch(e) {
alert("won't work");
}

Error Object

When an error occurs, JavaScript creates an object that is called an error object. There are three parameters in the error object

  1. name: Error type’s
javaScript
//"ReferenceError": an undefined variable.
const name = "HTML"
name = "CSS"
//TypeError: Assignment to constant variable.
cons num = "33"
//SyntaxError: Unexpected identifier

2. message: A string with the error message

3. stack: It’s a debugging tool that shows you call stack. It doesn’t only show you where the error happened, but also how the program ended up in that place of the code.

try {   
java; // error, variable is not defined!
} catch(err) {
alert(err.name); // ReferenceError
alert(err.message); // java is not defined
alert(err.stack);// ReferenceError: java is not defined at (...call stack)

Optional Catch Binding

If you don’t need error details, you can use below syntax without using error object.

try {
//code
}
catch {
//without error
}

Real Case of using try…catch

when we get data from a server, it is in JSON format. Then we convert it into js object by JSON.parse(data). But, if we get bad JSON data, it dies. people don’t like any error without error message. Here, you can use try..catch by showing an error message.

const data = "{ bad JSON }";  
try {
let user = JSON.parse(data); // an error occurs...
alert( user.name ); // doesn't work
}
catch (e) {
alert( "Our apologies, the data has errors, we'll try to request it one more time." );
alert( e.name );
alert( e.message );

Throwing Own Error

“throw” is used for user-defined errors. Like you get a JSON data without name property but you call for name value that occurs error. This type error is SyntaxError, so you can handle it by using the throw statement.

const data = '{ "age": 33 }'; // incomplete data  
try {
let user = JSON.parse(data); //
if (!user.name) {
throw new SyntaxError("Incomplete data: no name"); // (*)
}
alert( user.name );
}
catch(e) {
alert( "JSON Error: " + e.message ); // JSON Error: Incomplete data: no name }

Rethrowing

If there is one more error unexpected error, you can use rethrow that means you can use double throw in your code. Here, “instanceof ” operator is used to check the error type.

const data= '{ "age": 33 }'; // incomplete data try {    const user = JSON.parse(data); 

if (!user.name) {

throw new SyntaxError("Incomplete data: no name");
}

python(); // unexpected error

alert( user.name );
}
catch(e) {

if (e instanceof SyntaxError) {

alert( "JSON Error: " + e.message );
}
else {

throw e; // rethrow (*)
}
}

try…catch…finally

There is one more clause is finally. It executes always whatever there is an error or no error.

try
{
// code that occurs error
}
catch(error)
{
// give error information
}
finally {
// execute always
}

Global Catch

If we have found an error outside of try…catch block, we can use a function to the window.onerror property.

window.onerror = function(message, url, line, col, error) {  
// ...
};

Here, message => error message

url => URL of the script where error happened.

line, col => Line and column numbers where the error happened.

error => error object.

A Front-end Developer