Custom Error (Throw)
When there's an error in a code, JavaScript generates an error message. Throw statement allows you to create your own custom error to provide more specific information about why the code or program failed.
const getAPIs = async () => {
try {
let response = await axios.get("url");
if (!response.ok) {
throw new Error("failed to fetch data");
}
console.log(response.data);
} catch (e) {
console.error(`custom error: ${e.message}`);
}
};
Global Error Handling
Global error handling allows you to catch and handle unhandled exceptions and errors that occur in your application. It can be used to display error messages to users, clean-up tasks, log errors, etc.
There are two methods to set up global error handling, and they are;
window.onerror: This is a global event handler that can be used to handle JavaScript runtime error. It allows you to catch and handle errors at the global level.
Window.onerror consists of five parameters that provide details about the error that occurred. They include;
message: The message associated with the thrown exception
source: The url of the script where error occurred
lineno: The line number where the error was thrown
colno: The column number where the error was thrown
error: The error object that contains information about the error
Example;
You can create a function and save it in window.onerror
window.onerror = function (message, source, lineno, colno, error) {
//perform other actions
console.log("lineNumber:", lineno);
};
window.addEventListener("error",handler): You can use the addEventListener() method on the window object to listen for errors , and handle them in a flexible manner.
The error event object also comes with properties like message, filename, colno, lineno, and error which provides detailed information about the error.
Example
window.addEventListener("error", function (event) {
//perform other actions
console.error(
" error:",
event.message,
event.filename,
event.lineno,
event.colno,
event.error
);
});
Error Object
In JavaScript there are built-in-error objects such as error, syntaxError, ReferenceError, TypeError, etc which can either be thrown or caught. Error object allows you to handle different types of errors like syntax error, reference error, type error, etc.
try {
//code that might throw an error
undefinedVariable.exponent();
} catch (error) {
if (error instanceof TypeError) {
console.error("TypeError:", error.message);
} else {
console.error("An error occured:", error.message);
}
}
In the above example, the code in the ‘try’ block might throw a TypeError or Reference error when the exponent function is called on undefinedVariable, which is not defined.
The catch block catches the error, the instanceof TypeError checks if the caught error is a TypeError and then logs the TypeError message, else, it logs a more generic error message.