繁体   English   中英

如何创建Node.js自定义错误并在res.json()之后返回堆栈属性

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM