Throwing Custom Errors

Published on: April 30, 2017

Welcome to the 45th Easy JavaScript tutorial, part of Let's look a little more into try...catch by looking at the throw() function which you can use to include your own custom error messages.

Custom errors can be defined by you based on logic that you've entered. You don't have to rely on the 5 basic errors that JavaScript tends to throw, make up your own! The throw() function in JavaScript makes it easy for you to offer more useful error messages for your end users. Not only that, it can be great for you as the developer because you can tell yourself exactly what you are expecting! The syntax is very easy and very clear, so let's take a look at what that would look like below. 

Syntax of try...catch...throw():

        //run code and validate something
        throw("Custom error message if validation failed");
    } catch (error) {
        //Do something the code can't run or returns an error
        //the error parameter chere is what the throw() function sent back 
        // or error.message do not work here, just look for error console.log(error); 
        //outputs: "Custom error message if validation failed" into the JS Console 

To fork the fiddle and follow along:

Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!