如何更改restify中的默认错误输出

有什么办法可以改变默认的错误输出吗? 说我要改变其余的错误输出:

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

至:

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

以下是我的一些想法:

  • 收听错误事件。
    似乎并非所有的RestError都发出了额外的事件(如NotFound,MethodNotAllowed,VersionNotAllowed … do)。 所以我不能抓住所有的错误来重写它们。

  • 在发送响应数据之前收听事件。
    我查阅了官方文件,发现没有什么亲戚。

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

任何其他的想法?

最后,我提供了一个自定义的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; } } } ); 

虽然上面的答案可能会起作用,但将自定义字段添加到错误主体的最简单方法是使用对象(hash)而不是string调用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'}})); 

Restify提供了很多方法来实现错误pipe理: http ://mcavage.github.io/node-restify/#Error-handling

为什么不像示例代码那样创build一个新的错误types“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,只是使用原型重载函数)

(编辑)的

我能够提供额外的数据添加属性的身体对象。 注意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); ` 

你可以使用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'} 

另请注意,所提供的解决scheme仅在restify 5.x进行testing

请按照此问题获取更多信息。