How to create custom errors in JavaScript ?
Last Updated :
22 Aug, 2022
In this article, we will learn to create custom errors with some examples.
Errors represent the state of being wrong in condition. Javascript handles a predefined set of errors by itself but if you want to create your own error handling mechanism you can do that with custom errors functionality available in javascript.
We make use of the OOPS concept called an inheritance to implement custom errors. All the types of standard errors like RangeError, TypeError, etc inherit a main class called Error, which looks as follows:
Syntax of Error Class Instance:
new Error(msg , filename , lineno);
where:
- msg: The error message.
- filename: The file where the error occurs.
- lineno: line number of the error.
The Error class consists of properties like name, message, filename, and methods like captureStackTrace, and toString. But again it is different in different browsers.
You can use this error class to construct your own error object prototype which is called as custom error.
Custom errors can be constructed in two ways, which are:
- Class constructor extending error class.
- Function constructor inheriting error class.
Class constructor extending error class: Here we define a class that extends the error class,
Syntax:
class CustomErrorName extends Error{
constructor ( ){
super( )
}
...
}
Example 1: We will create an error for a condition 10 != 20 in the below code.
JavaScript
class CheckCondition extends Error {
constructor(msg) {
super(msg);
}
}
try {
if (10 != 20)
throw new CheckCondition("10 is not equal to 20");
}
catch (err) {
console.error(err);
}
Output:
OUTPUTFunction constructor inheriting error class:
Here the function inherits the prototype of the error class. we can then create other custom properties and methods to handle the application-specific error.
Syntax:
function CustomErrorName(msg = "") {
this.message = msg;
this.name = "CustomErrorName";
}
CustomErrorName.prototype = Error.prototype;
Example 2: In this example, we will create a custom error that throws for the condition 10 != 20.
JavaScript
function CheckCondition(msg = "") {
this.msg = msg;
this.name = "CheckCondition";
}
CheckCondition.prototype = Error.prototype;
try {
if (10 != 20)
throw new CheckCondition("10 is not equal to 20");
}
catch (err) {
console.error(err);
}
Output:
OUTPUT
In this way, we can create errors specific to our applications in javascript and by making some conditions we can throw the custom errors whenever the users of the applications make a mistake in using the applications.
Similar Reads
How to Create Customizable Alerts in JavaScript ? Alerts in JavaScript are an important components in web design. They are commonly used to notify users. The SweetAlert2 library aims to make basic looking alerts much more attractive and also provide context to the alert. The documentation and usage examples of SweetAlert2 could be found here. Insta
2 min read
How to create a Custom Error Page in Next.js ? Creating a custom error page in Next.js allows you to provide a better user experience by customizing the appearance and messaging of error pages like 404 and 500.In this post we are going to create a custom error page or a custom 404 page in a Next JS website.What is a custom error page?The 404 pag
2 min read
How to Catch JSON Parse Error in JavaScript ? JSON (JavaScript Object Notation) is a popular data interchange format used extensively in web development for transmitting data between a server and a client. When working with JSON data in JavaScript, it's common to parse JSON strings into JavaScript objects using the JSON.parse() method. However,
1 min read
How to Handle Errors in JavaScript? In JavaScript Error Handling is used to find the errors in the code so, that the coder can find the particular issue to resolve it. Here are the different approaches to handle errors in JavaScript1. Using try catch and finally statementThe try, catch, and finally blocks are used for error handling.
4 min read
How to Create an Alert in JavaScript ? The alert() method in JavaScript displays an alert box with a message and an OK button. It's used when you want information to come through to the user, providing immediate notifications or prompts for user interaction during program execution. Note: Alert boxes interrupt user interaction, shifting
1 min read
How To Create Custom Error Handler Middleware in Express? In ExpressJS there is a built-in class named CustomError which is basically used to create an error of your choice. in this article, we will see how with the use of this CustomError class we can create a custom error handler middleware in ExpressJS.What is a CustomError Handler?A custom error handle
5 min read
How to escape try/catch hell in JavaScript ? In this article, we will try to understand how we may escape from multiple try/catch hell (that is multiple sequences of occurrences of try/catch blocks) in JavaScript. Let us first quickly visualize how we may create a try/catch block in JavaScript using the following illustrated syntax: Syntax: Fo
4 min read
JavaScript Error() constructor Javascript Error() constructor is used to create a new error object. Error objects are arising at runtime errors. The error object also uses as the base object for the exceptions defined by the user. Syntax: new Error([message[, fileName[, lineNumber]]]) Parameters: message: It contains information
2 min read
How to debug JavaScript File ? Debugging is essential because there are many errors that are not giving any kind of messages so to find out that we debug the code and find out the missing point. Example 1: Â Using console.log() Method In this, we can find out the error by consoling the code in various places. Using a console is on
2 min read
JavaScript AggregateError object The JavaScript AggregateError object is used to reflect the overall error of many single errors. This can be used when multiple errors need to be represented in the form of a combined error, for example, it can be thrown by Promise.any() when all the promises passed to it are rejected. Construction:
2 min read