Is there any way that I can change the default error output? Say I'm going to change the rest error output:
{
"code": "InvalidArgumentError",
"message": "blah blah..."
}
to:
{
"code": 10001,
"message": "blah blah",
"extraMsg": "blah blah"
}
Here are some of my ideas:
Listen to the error events.
It seems like not all the RestError have emitted extra events (like NotFound, MethodNotAllowed, VersionNotAllowed... do). So I can't catch all the errors to rewrite them.
Listen to an event before response data sent.
I look through the official documents and have found nothing relative.
Modify the implementation of the RestError class.
Well it's obviously not a good approach.
Any other ideas?
Finally I provide a customized JSON formatter to get what I want:
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;
}
}
} );