如何在NodeJs/Express中捕获这个错误?

3

我正在尝试使用NodeJs编写简单的Web服务。我使用以下方式进行Ajax调用:

$.ajax({
    type: "POST",
    url: "http://localhost:3800",

    // this json below is invalid and I need to verify it on server side
    data: '"jhhjh":"ssss"}',

    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){ console.log(data);
    },
    failure: function(errMsg) {
        console.log(errMsg);
    }
});

然后在服务器端我有这段代码:

var express = require("express"),
    app = express(),
    bodyParser = require('body-parser');


app.use(bodyParser());

app.all('/', function(req, res, next) {
    // set origin policy etc so cross-domain access wont be an issue

    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

    // that is the line that gives me error message and cannot return anything back to client
    res.send("all good");
});

app.post('/', function(req, res) {


});

app.listen(process.env.PORT || 3800);

然而,由于我试图传递给服务器的json无效,我的Express崩溃了,我对此无能为力。 我无法捕获它或任何东西。 如何捕获此错误?

Error: invalid json
    at parse (C:\xampp\htdocs\testing\node_modules\body-parser\index.js:60:15)
    at C:\xampp\htdocs\testing\node_modules\body-parser\index.js:156:18
    at IncomingMessage.onEnd (C:\xampp\htdocs\testing\node_modules\body-parser\node_modules\raw-body\index.js:113:7)
    at IncomingMessage.g (events.js:180:16)
    at IncomingMessage.EventEmitter.emit (events.js:92:17)
    at _stream_readable.js:920:16
    at process._tickCallback (node.js:415:13)

我该如何捕获这个错误?我的需求是检测传递的json是否无效,如果无效则返回400和json消息{"someerror":"somemessage"}


2
你尝试过添加Express错误处理程序吗?app.use(function(err, req, res, next) { /* check err */ }); - mscdex
是的,它什么也没做 :( - spirytus
你在哪里添加了错误处理程序?一般我会在中间件栈的末尾和路由之后添加一个。 - mscdex
1个回答

3
在 server.js 中尝试以下代码:
var express = require("express"),
app = express(),
bodyParser = require('body-parser');

app.use(bodyParser());
app.use(function(err,req,res,next){
if(err){
    console.log(err);
}
next();
});

app.all('/', function(req, res, next) {
    // set origin policy etc so cross-domain access wont be an issue

    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,  Content-Type, Accept");
    console.log(req.body);
    next();
});
app.post('/', function(req, res) {
    if(!Object.keys(req.body))
        res.json('all good');
    else
        res.json({
            success: false,
            error: "json invalid"
        }, 400);


});



app.listen(process.env.PORT || 3800);

1
您真是个天才!有趣的是(对于那些观察我几个小时的人来说很有趣,但对我来说不太有趣),我使用了类似的 app.use(fu...) 调用,但它从未被触发。现在它可以工作了,我只是试图找出我哪里做错了。谢谢! - spirytus
@spirytus 很高兴能帮助 :) - azero0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接