[英]How to create Node.js custom errors and have the stack property return after res.json()
我試圖在使用Error作為原型的Node中創建自定義錯誤對象,然后通過express res.json()
方法將這些錯誤返回給客戶端。 我可以創建一個自定義錯誤的實例,設置它的屬性,但是當我調用res.json()
,缺少堆棧屬性。 我相信這是由於JSON.stringify()
沒有遵循原型嗎?
我看不到創建具有任意數量的屬性的自定義錯誤對象,然后在這些對象上使用JSON.stringify()
返回所有屬性以及基類/超類Error
堆棧屬性的方法。 請幫忙! 下面是一個示例:
(function (customErrorController) {
function CustomError() {
this.name = 'CustomError'; // String
this.message = null; // String
this.errorCode = null; // String
// this.stack exists as CustomError inherits from Error
}
CustomError.prototype = new Error();
customErrorController.init = function (app) {
app.get('/test', function (req, res) {
var customError = new CustomError();
customError.message = 'The Message';
customError.errorCode = 'Err001';
console.log(customError.stack); // This logs the stack fine
res.json(customError); // The stack is missing when outputting the object as JSON
});
};
})(module.exports);
感謝您的評論。 從這些以及更多的挖掘中,我現在正在使用以下代碼創建自定義錯誤,並在調用帶有錯誤的res.json()
之后返回正確的堆棧堆棧屬性:
// Redefine properties on Error to be enumerable
Object.defineProperty(Error.prototype, 'message', { configurable: true, enumerable: true });
Object.defineProperty(Error.prototype, 'stack', { configurable: true, enumerable: true });
(function (customErrorController) {
function CustomError(message, errorCode) {
Error.captureStackTrace(this, CustomError);
this.name = 'CustomError'; // String
this.message = message; // String
this.errorCode = errorCode; // String
}
CustomError.prototype = Object.create(Error.prototype);
customErrorController.init = function (app) {
app.get('/test', function (req, res) {
var customError = new CustomError('The Message', 'Err001');
res.json(customError); // The stack property is now included
});
};
})(module.exports);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.