Search code examples
node.jsexpressmongoosemiddlewarerestify

express-restify-mongoose error propogation


I am having a problem serving up error messages using express-mongoose-restify.

My schema has a hook like

myschema.pre('save', function(next){
    // If validation fails
    next(new Error('failed to validate model'))
})

For error handling I have (something similar to) the following code

resify.serve(express.Router(), mongoose.model('myschema', {
    onError: function(err, req,res,next){
        console.log(err)
        res.status(400).json(err)
    }
})

The output to the console when validation fails is as follows:

{ [Error: failed to validate model] statusCode : 400 }

In my client I have the following (jquery) ajax error handler:

$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
    console.log(jqxhr)
    console.log(thrownError)
});

thrownErorr is equal to "Bad Request" and jqxhr has reseponseText: "{"statusCode" : 400}" similar (but parsed to JS) for the responseJSON. The message failed to validate model is not being sent to the client. I think that I am misunderstanding the type of object that err is in my sever side error handler. Any thoughts? Thanks in advance!


Solution

  • This is one of those cases where writing the question made me think of the right question to ask myself in order to answer it.

    The V8 error object that is use by node does not send the additional information such as the stack, message etc when converted to JSON. My problem was solved by reading up on the properties of the Error object here.

    In particular using the following handler, the error is successfully relayed to the client

    onError : function(err, req, res, next){
        res.status(400).json({
          message : err.message,
          stack : err.stack
        })
      }