【问题标题】:express-restify-mongoose error propogationexpress-restify-mongoose 错误传播
【发布时间】:2015-11-16 11:53:10
【问题描述】:

我在使用 express-mongoose-restify 提供错误消息时遇到问题。

我的架构有一个类似的钩子

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

对于错误处理,我有(类似于)以下代码

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

验证失败时向控制台输出如下:

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

在我的客户端中,我有以下 (jquery) ajax 错误处理程序:

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

thrownErorr 等于 "Bad Request"jqxhrreseponseText: "{"statusCode" : 400}" 类似(但解析为 JS)的 responseJSON。消息failed to validate model 未发送到客户端。我认为我误解了err 在我的服务器端错误处理程序中的对象类型。有什么想法吗?提前致谢!

【问题讨论】:

    标签: node.js express mongoose middleware restify


    【解决方案1】:

    这是写问题让我想到要问自己的正确问题以回答问题的情况之一。

    节点使用的 V8 错误对象在转换为 JSON 时不会发送附加信息,例如堆栈、消息等。通过阅读Error 对象here 的属性,我的问题得到了解决。

    特别是使用以下处理程序,错误已成功中继到客户端

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

    【讨论】:

      猜你喜欢
      • 2017-06-04
      • 2019-07-22
      • 1970-01-01
      • 2012-12-22
      • 2015-11-17
      • 2021-03-17
      • 2014-12-23
      • 2021-12-20
      • 2020-07-30
      相关资源
      最近更新 更多