In this example, We will learn how to utilize the Error objects in JavaScript. Depending on the type of error, you may be able to use the name and message properties to get a more refined message.
The name property provides the general class of Error (such as DOMException or Error), while message generally provides a more succinct message than one would get by converting the error object to a string.
If you are throwing your own exceptions, in order to take advantage of these properties (such as if your catch block doesn’t discriminate between your own exceptions and system ones), you can use the Error constructor.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function doSomethingErrorProne() { if (ourCodeMakesAMistake()) { throw (new Error('The message')); } else { doSomethingToGetAJavascriptError(); } } ⋮ try { doSomethingErrorProne(); } catch (e) { // NOW, we actually use `console.error()` console.error(e.name); // logs 'Error' console.error(e.message); // logs 'The message', or a JavaScript error message } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.