node-restify: Modifying errors before they are displayed
Hi,
I’d like to be able to change how errors are displayed. At the moment they look like that:
{"code":"InvalidSession","message":"Invalid Session"}
I’d like to be able to display something like that instead:
{"error":{"code":"InvalidSession","message":"Invalid Session"}}
I created custom errors that extend restify.RestError, which I use in my routes (GET/POST/…) via:
next( new InvalidSessionError() );
Is it possible to get my hands on the javascript object before it is stringified to JSON and simply modify it?
Is there some sort of parameter that contains the output? Ideally it’d look like that:
response.output = { error: response.output };
I had 2 ideas for how this could be achieved:
-
Custom Formatter - It’d be best if I could do it without having to create a formatter from scratch for application/json, i.e to create a formatter which only modifies the javascript object and then passes it to the existing application/json formatter. I tried my hand at it and failed.
-
Listening to an event via server.on where hopefully I’ll be able to modify it somehow. When I listen to ‘InternalServer’ it is never called.
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Comments: 15 (7 by maintainers)
Sorry for the delayed reply - it depends on the formatter you are using for that response. i.e., if you are depending the default JSON formatter, all it does is call JSON.stringify(). To change that output, you could simply implement toJSON for the error you want to format: