我可以在JavaScript中为用户定义的异常定义自定义类型吗?如果可以的话,我该怎么做?
出于某种原因,看起来构造函数委派在以下代码段中不起作用:
function NotImplementedError() {
Error.apply(this, arguments);
}
NotImplementedError.prototype = new Error();
var nie = new NotImplementedError("some message");
console.log("The message is: '"+nie.message+"'")
Run Code Online (Sandbox Code Playgroud)
运行这个给出The message is: ''.有关为什么,或者是否有更好的方法来创建新Error子类的任何想法?是否存在我不知道apply的本机构Error造函数的问题?
我试图用ES6和Babel扩展Error.它没有成功.
class MyError extends Error {
constructor(m) {
super(m);
}
}
var error = new Error("ll");
var myerror = new MyError("ll");
console.log(error.message) //shows up correctly
console.log(myerror.message) //shows empty string
Run Code Online (Sandbox Code Playgroud)
Error对象永远不会获得正确的消息集.
现在我已经在SO上看到了一些解决方案(例如这里),但它们看起来都非常非ES6-y.如何以漂亮的ES6方式做到这一点?(那是在Babel工作)
你将如何实现不同类型的错误,这样你就能捕捉到特定错误并让其他人冒出来......?
实现此目的的一种方法是修改Error对象的原型:
Error.prototype.sender = "";
function throwSpecificError()
{
var e = new Error();
e.sender = "specific";
throw e;
}
Run Code Online (Sandbox Code Playgroud)
捕获特定错误:
try
{
throwSpecificError();
}
catch (e)
{
if (e.sender !== "specific") throw e;
// handle specific error
}
Run Code Online (Sandbox Code Playgroud)
你有没有其他选择?
在JavaScript中,我们有几种获取对象属性的方法,具体取决于我们想要获得的内容.
1)Object.keys(),它返回一个对象的所有自己的可枚举属性,一个ECMA5方法.
2)一个for...in循环,它返回一个对象的所有可枚举属性,无论它们是自己的属性,还是从原型链继承.
3)Object.getOwnPropertyNames(obj)返回对象的所有属性,可枚举与否.
我们也有这样的方法hasOwnProperty(prop)让我们检查属性是继承还是实际属于该对象,propertyIsEnumerable(prop)顾名思义,它让我们检查属性是否可枚举.
有了所有这些选项,就无法获得对象的不可枚举的非自有属性,这就是我想要做的.有没有办法做到这一点?换句话说,我可以以某种方式获取继承的非可枚举属性的列表吗?
谢谢.
有许多关于如何在使用JavaScript Promise进行编程时使用"then"和"catch"的教程.但是,所有这些教程似乎都错过了重要的一点:从then/catch块返回以打破Promise链.让我们从一些同步代码开始来说明这个问题:
try {
someFunction();
} catch (err) {
if (!(err instanceof MyCustomError))
return -1;
}
someOtherFunction();
Run Code Online (Sandbox Code Playgroud)
本质上,我正在测试一个捕获的错误,如果不是错误,我希望我将返回调用者,否则程序继续.但是,这种逻辑不适用于Promise:
Promise.resolve(someFunction).then(function() {
console.log('someFunction should throw error');
return -2;
}).catch(function(err) {
if (err instanceof MyCustomError) {
return -1;
}
}).then(someOtherFunction);
Run Code Online (Sandbox Code Playgroud)
这个逻辑用于我的一些单元测试,我希望函数以某种方式失败.即使我将catch更改为then块,我仍然无法打破一系列链接的Promises,因为从then/catch块返回的任何内容都将成为沿着链传播的Promise.
我想知道Promise是否能够实现这个逻辑; 如果没有,为什么?对我来说,Promise链永远不会被破坏是很奇怪的.谢谢!
编辑于2015年8月16日:根据到目前为止给出的答案,由then块返回的被拒绝的Promise将通过Promise链传播并跳过所有后续块,直到被捕获(处理).这种行为很好理解,因为它只是模仿以下同步代码(方法1):
try {
Function1();
Function2();
Function3();
Function4();
} catch (err) {
// Assuming this err is thrown in Function1; Function2, Function3 and Function4 will not be executed
console.log(err);
}
Run Code Online (Sandbox Code Playgroud)
但是,我要问的是同步代码中的以下场景(方法2):
try {
Function1();
} catch(err) {
console.log(err); // Function1's error …Run Code Online (Sandbox Code Playgroud) 如何在nodejs/javascript中重新抛出错误或异常并包含自定义消息.
我有以下代码
var json = JSON.parse(result);
Run Code Online (Sandbox Code Playgroud)
result如果发生任何解析错误,我想在异常消息中包含内容.像这样的东西.
1. try {
2. var json = JSON.parse(result);
3. expect(json.messages.length).to.be(1);
4. } catch(ex) {
5. throw new Error(ex.message + ". " + "JSON response: " + result);
6. }
Run Code Online (Sandbox Code Playgroud)
这里的问题是我丢失了堆栈跟踪.
有没有办法做到这一点java?
throw new Error("JSON response: " + result, ex);
Run Code Online (Sandbox Code Playgroud) Douglas Crockford建议做这样的事情:
throw {
name: "System Error",
message: "Something horrible happened."
};
Run Code Online (Sandbox Code Playgroud)
但你也可以这样做:
function IllegalArgumentException(message) {
this.message = message;
}
throw new IllegalArgumentException("Argument cannot be less than zero");
Run Code Online (Sandbox Code Playgroud)
然后做:
try {
//some code that generates exceptions
} catch(e) {
if(e instanceof IllegalArgumentException) {
//handle this
} else if(e instanceof SomeOtherTypeOfException) {
//handle this
}
}
Run Code Online (Sandbox Code Playgroud)
我想你可以type在Crockford的实现中包含一个属性,然后检查它而不是做一个instanceof.做一个对另一个有什么好处吗?
在我的NodeJS程序中,我解析了一些用户JSON文件.
所以我使用:
this.config = JSON.parse(fs.readFileSync(path));
Run Code Online (Sandbox Code Playgroud)
问题是如果json文件没有正确格式化,抛出的错误就像:
undefined:55
},
^
SyntaxError: Unexpected token }
at Object.parse (native)
at new MyApp (/path/to/docker/lib/node_modules/myApp/lib/my-app.js:30:28)
...
Run Code Online (Sandbox Code Playgroud)
由于它不是真正的用户友好,我想抛出一个Error指定一些用户友好的消息(如"你的配置文件没有很好的格式化"),但我想保持堆栈跟踪,以指向有问题的行.
在我使用的Java世界throw new Exception("My user friendly message", catchedException)中,为了得到导致那个的原始异常.
JS世界怎么可能?
我正在开发一个小型JS库,并在那里使用自定义错误异常.
那么,我决定以这种方式从本机Javascript Error对象继承它们(ORLY?):
var MyError = function(){
Error.prototype.constructor.apply(this, arguments);
};
// Inherit without instantiating Error
var Surrogate = function(){};
Surrogate.prototype = Error.prototype;
MyError.prototype = new Surrogate();
// Add some original methods
MyError.prototype.uniqueMethod = function(){...}
Run Code Online (Sandbox Code Playgroud)
看起来像平常的继承..但是!
var err = new MyError("hello! this is text!");
console.log(err.message); // is giving me empty string!
Run Code Online (Sandbox Code Playgroud)
我已经在这里和MDN上阅读了有关此内容的文章,但所有人都说我要使用这样的东西:
var MyError = function(msg){
this.message = msg;
};
Run Code Online (Sandbox Code Playgroud)
但我的问题是 - 如果不是在Error的构造函数中,那么消息初始化的地方?可能有人知道Error本机构造函数是如何工作的?
谢谢!
PS如果它有趣 - 我正在开发Enum.js库.
javascript ×10
exception ×4
node.js ×2
asynchronous ×1
babeljs ×1
ecmascript-6 ×1
expect.js ×1
inheritance ×1
native ×1
object ×1
oop ×1
promise ×1
properties ×1
stack-trace ×1
transpiler ×1