2013-05-14 8 views
8

Esiste un modo per modificare l'output di errore predefinito? Dire che ho intenzione di cambiare l'output di errore resto:Come modificare l'output di errore predefinito in Restify

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

a:

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

Ecco alcune delle mie idee:

  • intercettare gli eventi di errore.
    Sembra che non tutti gli oggetti RestError abbiano emesso eventi aggiuntivi (come NotFound, MethodNotAllowed, VersionNotAllowed ... do). Quindi non riesco a cogliere tutti gli errori per riscriverli.

  • Ascoltare un evento prima dei dati di risposta inviati.
    Guardo tra i documenti ufficiali e non ho trovato nulla di relativo.

  • Modificare l'implementazione della classe RestError.
    Beh, ovviamente non è un buon approccio.

Altre idee?

risposta

3

Restify offrono molti modi per implementare la gestione degli errori: http://mcavage.github.io/node-restify/#Error-handling

Perché non si crea un nuovo tipo di errore "myError" proprio come codice di esempio:

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); 

per gli errori comuni penso che i metodi di sovraccarico non sono una cattiva idea ... (Non parlo di modificare la restituzione, solo sovraccaricare le funzioni usando il prototipo)

(a cura di)

+0

Estendere RestError per creare un nuovo tipo di errore non aiuta a risolvere il mio problema. Forse proverò a sovraccaricare le funzioni usando il prototipo. Grazie! –

+0

Dopo molte ricerche e un po 'di esperienza con la restituzione, darò questo risultato mentre il formattare con i formattatori sembra un po' eccessivo. –

11

Infine ho fornire un formattatore JSON personalizzato per ottenere ciò che voglio:

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; 
     } 
    } 
}); 
+0

Questo ha funzionato perfettamente. Grazie molto! –

1

sono stato in grado di fornire dati aggiuntivi aggiunta di una proprietà per l'oggetto corpo. Avviso il this.body.errors = errors linea

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

Mentre le risposte di cui sopra potrebbero funzionare, il modo più semplice per aggiungere un campo personalizzato per il corpo errore è di chiamare il costruttore errore restify con un oggetto (hash) invece di una stringa. L'oggetto deve contenere la chiave body che è ciò che vedrai nel browser.

Ad esempio:

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

o

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

È possibile utilizzare restify-errors-options

Il vostro esempio diventa semplicemente:

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'} 

Si prega di notare anche t la soluzione fornita è stata testata solo su restify 5.x

Per ulteriori informazioni, seguire questo numero issue.