【问题标题】:How to change the default error output in restify如何更改restify中的默认错误输出
【发布时间】:2013-05-08 13:14:42
【问题描述】:

有什么方法可以更改默认错误输出?假设我要更改其余错误输出:

{
    "code": "InvalidArgumentError",
    "message": "blah blah..."
}

到:

{
    "code": 10001,
    "message": "blah blah",
    "extraMsg": "blah blah"
}

以下是我的一些想法:

  • 监听错误事件。
    似乎并非所有 RestError 都发出了额外的事件(如 NotFound、MethodNotAllowed、VersionNotAllowed ......做)。所以我无法捕获所有错误来重写它们。

  • 在发送响应数据之前监听事件。
    翻遍了官方文档,没有找到相关的。

  • 修改 RestError 类的实现。
    好吧,这显然不是一个好方法。

还有其他想法吗?

【问题讨论】:

    标签: node.js restify


    【解决方案1】:

    最后我提供了一个自定义的 JSON 格式化程序来得到我想要的:

    var server = restify.createServer( {
        formatters: {
            'application/json': function customizedFormatJSON( req, res, body ) {
                // Copied from restify/lib/formatters/json.js
    
                if ( body instanceof Error ) {
                    // snoop for RestError or HttpError, but don't rely on
                    // instanceof
                    res.statusCode = body.statusCode || 500;
    
                    if ( body.body ) {
                        body = {
                            code: 10001,
                            scode: body.body.code,
                            msg: body.body.message
                        };
                    } else {
                        body = {
                            code: 10001,
                            msg: body.message
                        };
                    }
                } else if ( Buffer.isBuffer( body ) ) {
                    body = body.toString( 'base64' );
                }
    
                var data = JSON.stringify( body );
                res.setHeader( 'Content-Length', Buffer.byteLength( data ) );
    
                return data;
            }
        }
    } );
    

    【讨论】:

      【解决方案2】:

      虽然上面的答案可能有效,但将自定义字段添加到错误正文的最简单方法是使用对象(哈希)而不是字符串调用 restify 错误构造函数。该对象必须包含您将在浏览器中看到的 body 键。

      例如:

      return next(new restify.InvalidArgumentError({body: {field: 'password', message: 'Password has to be at least 6 characters long'}}));
      

      return next(new restify.UnauthorizedError({body: {foo: 'bar', name: 'john doe', message: 'whatever error message'}}));
      

      【讨论】:

        【解决方案3】:

        Restify 提供多种方式来实现错误管理:http://mcavage.github.io/node-restify/#Error-handling

        为什么不创建一个新的错误类型“myError”,就像示例代码一样:

        var restify = require('restify');
        var util    = require('util');
        
        function MyError(message) {
          restify.RestError.call(this, {
            restCode      : 'MyError',
            statusCode    : 418,
            message       : message,
            constructorOpt: MyError
          });  
          this.name = 'MyError';
        }
        
        util.inherits(MyError, restify.RestError);
        

        对于常见错误我认为重载方法并不是一个坏主意......(我不说修改restify,只是使用原型重载函数)

        (已编辑)

        【讨论】:

        • 扩展 RestError 以创建新的错误类型无助于解决我的问题。也许我会尝试使用原型重载函数。谢谢!
        • 经过大量研究和一些关于 restify 的经验后,我会试一试,因为对格式化程序的处理似乎有点困难。
        【解决方案4】:

        我能够提供附加数据,将属性添加到 body 对象。 注意this.body.errors = errors

        var restify = require('restify');
        var util = require('util');
        
        function ValidationError(message, errors) {
            restify.RestError.call(this, {
                restCode: 'ValidationError',
                statusCode: 400,
                message: message,
                constructorOpt: ValidationError
            });
            this.name = 'ValidationError';
            this.body.errors = errors; //<---
        }
        
        util.inherits(ValidationError, restify.RestError);
        `
        

        【讨论】:

          【解决方案5】:

          您可以使用restify-errors-options

          你的例子就变成了:

          const restify = require('restify');
          const errors = require('restify-errors');
          const errorsOptions = require('restify-errors-options');
          
          errorsOptions.add('extraMsg');
          const err = new errors.BadRequestError({extraMsg: 'whatever you want'});
          
          err.toJSON();
          //=> {code: 'BadRequest', message: '', extraMsg: 'whatever you want'}
          

          另请注意,提供的解决方案仅在 restify 5.x 上测试过

          关注issue了解更多信息。

          【讨论】:

            猜你喜欢
            • 2016-12-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-05-08
            • 2012-08-28
            • 2020-06-06
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多