Javascript Error Handling

No matter how great we are at programming, sometimes our code has errors. They may occur because of our mistakes, an unexpected user input, an erroneous server response, and for a thousand other reasons.

Javascript has try and catch to handle these errors and respond to users.

try {
    let name = getName();
} catch (error) {
    /*
    * error object that contains at least the name of the error and message that explains the error in detail.
    * Different web browsers may add more property to the error object. 
    * For example, Firefox adds filename, lineNumber, and stack properties to the error object.
    */
    console.log(error);//ReferenceError: getName is not defined
    console.log(error.name + ":" + error.message);//ReferenceError:getName is not defined
}finally {
    console.log("finally");
}

Try and Catch only works synchronously and does not work asynchronously.

/*
* try..catch only works synchronously. It does not work asynchronously.
*/

try {
    setTimeout(function() {
        getName(); // script will die here
    }, 1000);
} catch (error) {
    console.log("Error not caught here.");
}

setTimeout(function() {
    try {
        getName();
    } catch (error) {
        console.log(error);//ReferenceError: getName is not defined
        console.log(error.name + ":" + error.message);//ReferenceError:getName is not defined
    }
}, 1000);

 

Throw an Error

Use throw new typeOfError to throw an error.

function throwError(){
    throw new Error("Something went wrong due to Error!");
}

function throwReferenceError(){
    throw new ReferenceError("Something went wrong due to ReferenceError!");
}

try {
    throwError();
} catch (error) {
    console.log(error.name + ":" + error.message);
}

try {
    throwReferenceError();
} catch (error) {
    console.log(error.name + ":" + error.message);
}

 

Types of Error

  • Error
  • EvalError – an error has occurred in the eval() function. Note: Newer versions of JavaScript does not throw any EvalError. Use SyntaxError instead.
  • RangeError – a number “out of range” has occurred
  • ReferenceError – an illegal reference has occurred
  • SystaxError – a syntax error has occurred
  • TypeError – a type error has occurred
  • URIError – an error in encodeURI() has occurred

Custom Error

You can create a custom error by extending the Error class

class ValidationError extends Error {
    constructor(message) {
        super(message); // (1)
        this.name = "ValidationError"; // (2)
    }
}

function testValidationError() {
    throw new ValidationError("Whoops!");
}

try {
    testValidationError();
} catch(error) {
    console.log(error.name + ":" + error.message);
    console.log("error stack");
    console.log(error.stack);
}

 

Source code on Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published.