admin管理员组文章数量:1394199
What is the correct way to define a custom error in JavaScript?
Searching through SO I've found about 6 different ways to define a custom error, but I'm unsure as to the (dis)advantages to each of them.
From my (limited) understanding of prototype inheritance in JavaScript, this code should be sufficient:
function CustomError(message) {
this.name = "CustomError";
this.message = message;
}
CustomError.prototype = Object.create(Error.prototype);
What is the correct way to define a custom error in JavaScript?
Searching through SO I've found about 6 different ways to define a custom error, but I'm unsure as to the (dis)advantages to each of them.
From my (limited) understanding of prototype inheritance in JavaScript, this code should be sufficient:
function CustomError(message) {
this.name = "CustomError";
this.message = message;
}
CustomError.prototype = Object.create(Error.prototype);
Share
Improve this question
asked Nov 25, 2014 at 2:32
n0wn0w
851 silver badge8 bronze badges
5
- somewhat related here stackoverflow./questions/783818/… – Netorica Commented Nov 25, 2014 at 2:34
-
that was the main SO question that confused me. the highest ranked answer lists two different ways for the custom error to inherit from the
Error
object, neither of which is using theObject.create()
method. the other answers seem to be variations of this theme. – n0w Commented Nov 25, 2014 at 2:38 -
1
Object.create
is merely a new way of doingCustomError.prototype = new Error()
-- developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – James Sumners Commented Nov 25, 2014 at 2:42 -
1
@n0w Related: Benefits of using
Object.create
for inheritance – Jonathan Lonowski Commented Nov 25, 2014 at 2:53 - See also stackoverflow./questions/1382107/… – Matt Browne Commented Nov 25, 2014 at 2:59
4 Answers
Reset to default 4The simplest of course, and in my opinion, the best to use unless you need more plex error reporting/handling is this:
throw Error("ERROR: This is an error, do not be alarmed.")
Usually I just use throw new Error(...)
, but for custom errors I find the following code works pretty well and still gives you stack traces on V8, i.e. in Chrome and node.js (which you don't get just by calling Error.apply()
as suggested in the other answer):
function CustomError(message) {
// Creates the this.stack getter
if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor)
this.message = message;
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;
CustomError.prototype.name = 'CustomError';
For more info, see these links:
What's a good way to extend Error in JavaScript?
https://plus.google./+MalteUbl/posts/HPA9uYimrQg
This script depicts all the possible mechanisms for creating and using custom errors in JavaScript.
Also to get a plete understanding, it's essential to have an understanding of prototypal inheritance and delegation in JavaScript. I wrote this article which explains it clearly. https://medium./@amarpreet.singh/javascript-and-inheritance-90672f53d53c
I hope this helps.
function add(x, y) {
if (x && y) {
return x + y;
} else {
/**
*
* the error thrown will be instanceof Error class and InvalidArgsError also
*/
throw new InvalidArgsError();
// throw new Invalid_Args_Error();
}
}
// Declare custom error using using Class
class Invalid_Args_Error extends Error {
constructor() {
super("Invalid arguments");
Error.captureStackTrace(this);
}
}
// Declare custom error using Function
function InvalidArgsError(message) {
this.message = `Invalid arguments`;
Error.captureStackTrace(this);
}
// does the same magic as extends keyword
Object.setPrototypeOf(InvalidArgsError.prototype, Error.prototype);
try{
add(2)
}catch(e){
// true
if(e instanceof Error){
console.log(e)
}
// true
if(e instanceof InvalidArgsError){
console.log(e)
}
}
function CustomError() {
var returned = Error.apply(this, arguments);
this.name = "CustomError";
this.message = returned.message;
}
CustomError.prototype = Object.create(Error.prototype);
//CustomError.prototype = new Error();
var nie = new CustomError("some message");
console.log(nie);
console.log(nie.name);
console.log(nie.message);
本文标签: Correct way to create custom errors in javascriptStack Overflow
版权声明:本文标题:Correct way to create custom errors in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744658804a2618119.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论