Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Error handling in Javascript

In this article, we will learn about the best practices which help to manage error handling in javascript. The errors are the part of any application and no programmer can ignore them, errors are more common and every programmer faces error all the time. Let’s make some best practices to handle the errors in the javascript.

Error types in javascript:
Let’s learn what are the major error type which is encountered in the javascript.

ReferenceError:
This error will be thrown when trying to use the variable which does not exist, and it creates an instance representing a ReferenceError

SyntaxError:
This error will be thrown when compiler finds an invalid code, and it creates an instance representing a SyntaxError

TypeError:
This error will be thrown when a variable or parameter is not of a valid type and it creates an instance representing TypeError

URIError:
Creates an instance representing an error that occurs when encodeURI() or decode URI() are passed invalid parameters.

InternalError:
Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown.

RangeError:
Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.

How to debug errors in the javascript?
Now we have learned what are error types in the javascript and where we can find the error details. Now it’s a time to learn how to debug the errors. When any error occurs in the application, the error details can be found at the Stack trace.

What is stack trace?
Its a report of the active stack frames at a certain point in time during the execution of a program.

Follow the below step to debug the errors in javascript:

Stack trace:
Observe the stack trace carefully and collect the error’s type, description, and file location and line number.

Go to the file:
Once error details been collected, go to the file and modify the code according to the error type.

Save and run:
After modification of a file, save and run.

How to avoid common errors in javascript?
Now we have learned about error types and how to debug the errors. Now there is a standard way of coding which can help in avoiding most of the common error types like ReferenceError and TypeError.

User try-catch block:
To avoid errors which stops your applications, we can use the try-catch block as follows:

const person = (param) => {
        if (!param) {
            throw Error('Param is required');
        }
        let home = param.adress.home;
        return home;

    };

    let personDetails = {
        email: 'John@test.com',
        address: {
            home: '#623 street'
        }
    };

    try {
        let homeAddress = person(personDetails);
        console.log(homeAddress);
    } catch (e) {
        console.log(e.message);
    }
    // output
    // Cannot read property 'home' of undefined

Check for empty values:
As we can observe in the above code snippet, we can check the param is empty or not with if.

const person = (param)=>{
        if(!param) {
            throw Error('Param is required');
        }
        let name = param.name;
        return name;

    };
    let personDetails = {
        name: 'John'
    };

    let name = person(personDetails);
    console.log(name);
    // output
    // john

Check if a property exists before accessing it in the object:
Without checking the property and accessing it, throws a below error:

const person = (param)=>{
        if(!param) {
            throw Error('Param is required');
        }
        let home = param.adress.home;
        return home;

    };
    let personDetails = {
        email: 'John@test.com',
        address: {
            home: '#623 street'
        }
    };

    let homeAddress = person(personDetails);
    console.log(homeAddress);
    // output
    // Uncaught TypeError: Cannot read property 'home' of undefined

reference error in javascript

Checking if a property exists and accessing it:

const person = (param)=>{
        if(!param) {
            throw Error('Param is required');
        }
        let home = param && param.adress && param.adress.home;
        return home;

    };
    
    let personDetails = {
        email: 'John@test.com',
        address: {
            home: '#623 street'
        }
    };

    let homeAddress = person(personDetails);
    console.log(homeAddress);
    // output
    // undefined