Hey Ninjas! You must have faced errors while practising any coding language. Have you ever tried to fix your error? The answer to this must be Yes. But have you thought about renaming your errors? For example, if you want to show any database error, you can use DbError. For network issues, you can use the HttpError, and so on.
Confused? Let's have deep dive into the world of error handling in Javascript. Our today's topic is Custom Error in Javascript.
Custom Error
As you can guess from the name, custom errors are user-made errors, where we can give names to the errors according to operations. Javascript supports basic error properties like name, message, and stack (optional). But these errors can be provided with the other properties that we desire. For example, the HttpError objects have a statusCode property with values like 404 or 403 or 500.
We can use the "throw" keyword in javascript with any argument. This implies that our custom error classes do not need to inherit from "Error." But if we inherit from the "Error" class, it becomes possible to use "obj instanceof Error" to identify error objects. So it is always better to inherit from the "Error" class.
Error Class
In this section, we will look at different types of custom errors. Let's start with a simple example. But before moving to an example, we will see the pseudo-code of the class Error. We will extend this class to make custom errors in the upcoming examples.
First, we have created a constructor with an argument called "message" in the Error class. Inside the constructor, there are three object instances where:
The first one indicates the "message" argument, which is assigned to the "message" property of the instance using the "this" keyword.
Next is the name argument, where you can mention the name of the error, like ValidationError or BadRequestError.
In the end, the "stack" property is given to the call stack at the point where the instance was created.
Extending Error Class
Now make the first custom error by inheriting the class Error. We will make a ServerError using this.
In this example, we have extended the Error class and created a custom class named "ServerError". As you can see in the output screen, both the message and the name of the error are shown in the Console.
You can also find this output on your system. Run the program in your IDE, go to the Inspect option in the browser, and click Console.
Conditional Error
We can also give conditions while generating errors. For example, if a specific condition is false, show the ValueNotFound error. Let's take an example for better understanding.
<!DOCTYPE html>
<head>
<title>Custom Errors</title>
</head>
<body>
<h2>Welcome to Coding Ninjas</h2>
</body>
<script>
class ValueNotFound extends Error {
constructor(message) {
super(message);
this.name = "ValueNotFound";
}
}
//Conditions
function myUser(json) {
let user = JSON.parse(json);
if (!user.fname) {
throw new ValueNotFound("No field: first name");
}
if (!user.lname) {
throw new ValueNotFound("No field: last name");
}
return user;
}
try {
//Input
let user = myUser('{ "fname": "Ninja" }');
} catch (err) {
//Possible Outputs inside Catch
if (err instanceof ValueNotFound) {
console.error("Error:" + err.name);
console.error("Invalid data: " + err.message);
} else if (err instanceof SyntaxError) {
console.error("JSON Syntax Error: " + err.message);
} else {
throw err;
}
}
</script>
</html>
Output:
Explanation:
In this example, the syntax of the input should be like this:
let json = `{ "fname": "Ninja", "lname": "Warrior" }`;
But notice in the try block we gave an incomplete input type which contains only the first name. Hence, in the output screen, an error came as a result.
We have added two more conditions in this example. If the syntax is not correct, it will show the SyntaxError with a message. Else it will throw a general error.
Multiple Inheritance
We can create more than one custom error at a time by extending the previous one. Let's have a look.
<!DOCTYPE html>
<head>
<title>Custom Errors</title>
</head>
<body>
<h2>Welcome to Coding Ninjas</h2>
</body>
<script>
//ValueNotFound class
class ValueNotFound extends Error {
constructor(message) {
super(message);
this.name = "ValueNotFound";
}
}
//PropertyNotFound class
class PropertyNotFound extends ValueNotFound {
constructor(property) {
super("No property: " + property);
this.name = "PropertyNotFound";
this.property = property;
}
}
//Conditions
function myUser(json) {
let user = JSON.parse(json);
if (!user.fname) {
throw new PropertyNotFound("Field Required: first name");
}
if (!user.lname) {
throw new PropertyNotFound("Field Required: last name");
}
return user;
}
//Inputs using try catch
try {
let user = myUser('{ "fname": "Ninja" }');
} catch (err) {
if (err instanceof ValueNotFound) {
console.error("Invalid data: " + err.message);
console.error("Error Name: " + err.name);
console.error(err.property);
} else if (err instanceof SyntaxError) {
console.error("JSON Syntax Error: " + err.message);
} else {
throw err;
}
}
</script>
</html>
Output:
Explanation:
As you can see, we have inherited the previous custom error ValueNotFound to the new custom error PropertyNotFound. Inside the try-catch, we again took the input and outputs.
Frequently Asked Questions
What are custom errors?
Custom errors are the errors defined by a user to suit the different operations in the system. These errors are used to make errors more meaningful.
Which class do we generally inherit from in custom error classes?
We generally inherit our custom error class from the "Error" class.
Which keyword do we use to compare custom errors with mainly defined errors?
We use the "instanceof" keyword to compare custom errors with standard errors.
What is meant by debugging?
Debugging is the process of removing errors or bugs from the program.
What are the exception-handling statements in Javascript?
The exception-handling statements in Javascript are try-catch, finally and throw.
Conclusion
This article discusses the topic of Custom errors in detail. We have seen the definition of Custom errors in starting. Along with this, we saw the error class and how we can extend the error class, conditional errors. We also covered multiple inheritances with code, output and explanation.
We hope this blog has helped you enhance your knowledge of Custom errors. If you want to learn more, then check out our articles.
But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problems, interview experiences, and interview bundles for placement preparations.
However, you may consider our paid courses to give your career an edge over others!