Categories
Featured Development Resources HTML/Javascript

JavaScript Error Handling And Throwing

Error handling in JavaScript can be a daunting topic if you’re new to programming, and there are a few caveats that can make it more difficult.

Throwing A Simple Error

The simplest way to throw an error is to just provide some text.

throw "This is my error"
// This is my error

Throwing An Error Object

A better way is to throw an Error object as we’ll see later on this works in more situations like when in asynchronous code.

throw new Error("This is my error")
// Error: This is my error

Throwing A Custom Error

You can define your own error classes and throw those errors using the name of the class.

class CustomError extends Error{
    constructor(msg) {
        super(msg);
        this.name = "CustomError"
    }
}

throw new CustomError("This is my custom error")
// CustomError: This is my custom error

Catching Errors

To catch errors we use the try…catch block.

The code that could throw an error is placed in try, and catch is executed if an error occurs, and finally is optional and always executed.

try {
    throw "this is an error"
} catch (e) {
    console.log(e)
} finally {
    console.log("Always executed")
}
// this is an error
// Always excuted

Dealing With Specific Errors

We can also process specific errors using the instanceof keyword and an if statement. The following example will only display a message if a CustomError is caught.

class CustomError extends Error {
    constructor(msg) {
        super(msg);
        this.name = "CustomError"
    }
}
try {
    throw new CustomError("this is a custom error")
} catch (e) {
    if(e instanceof CustomError) {
        console.log(e)
    }
} finally {
    console.log("Always executed")
}
// CustomError: this is a custom error
// Always executed

Throwing an error from an asynchronous function requires us to use the await.

This is done by wrapping the error that we want throw in an asynchronous function then when the error is thrown we obtain the desired result.

Throwing Errors In Asynchronous JavaScript

async function throwError() {
    throw new Error("I'm throwing asynchronously")
}

async function asynchronousFunc() {
    return await throwError()
}

async function executor() {
    await asynchronousFunc()
}

executor()
// Error: I'm throwing asynchronously

Error Handling In Promises And Fetch

JS promises and functions based on promises like fetch have their own built in error handling using catch like this.

new Promise(() => {
    throw "error";
}).catch((e) => console.log(`We have an ${e}`)); 
// We have an error

Conclusion

Basic error handling in JavaScript is similar to other languages and handled within try..catch blocks.

Sometimes strange events can occur when we handling errors within asynchronous code, and we need to remember to await the thrown error.

Promises make error handling easy with their own built in handling with .catch.