我看到以下,关于javscript,对象数据属性属性
- 可配置属性:指定是否可以删除或更改属性. - Enumerable:指定是否可以在for/in循环中返回该属性. - 可写:指定是否可以更改属性.
这里"Configurable Attribute"和"Writable"表示相同(属性是否可以更改),那么为什么我们需要两个单独的属性?
在我们的NodeJS应用程序中,我们通过扩展默认的Error对象来定义自定义错误类:
"use strict";
const util = require("util");
function CustomError(message) {
Error.call(this);
Error.captureStackTrace(this, CustomError);
this.message = message;
}
util.inherits(CustomError, Error);
Run Code Online (Sandbox Code Playgroud)
这使我们能够throw CustomError("Something");与堆栈跟踪正确显示出来,并且都instanceof Error和instanceof CustomError正常工作。
但是,为了通过我们的API返回错误(通过HTTP),我们希望将错误转换为JSON。调用JSON.stringify()错误会导致"{}",这显然对消费者而言并不是真正的描述。
为了解决这个问题,我想到了重写CustomError.prototype.toJSON(),以返回带有错误名称和消息的对象文字。JSON.stringify()然后只需将这个对象字符串化,一切都会很好:
// after util.inherits call
CustomError.prototype.toJSON = () => ({
name : "CustomError",
message : this.message
});
Run Code Online (Sandbox Code Playgroud)
但是,我很快就看到这引发了TypeError: Cannot assign to read only property 'toJSON' of Error。在我尝试编写原型时这可能很有意义。所以我改了构造函数:
function CustomError(message) {
Error.call(this);
Error.captureStackTrace(this, CustomError);
this.message = message;
this.toJSON = () => …Run Code Online (Sandbox Code Playgroud)