node.js 捕获 express bodyParser 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15819337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:06:50  来源:igfitidea点击:

Catch express bodyParser error

javascriptnode.jsexpress

提问by Gabriel Llamas

I want to catch the error from the bodyParser() middleware when I send a json object and it is invalid because I want to send a custom response instead of a generic 400 error.

我想在发送 json 对象时从 bodyParser() 中间件中捕获错误,但它无效,因为我想发送自定义响应而不是通用 400 错误。

This is what I have and it works:

这就是我所拥有的并且它有效:

app.use (express.bodyParser ());
app.use (function (error, req, res, next){
    //Catch bodyParser error
    if (error.message === "invalid json"){
        sendError (res, myCustomErrorMessage);
    }else{
        next ();
    }
});

But this seems to me a very ugly approach because I'm comparing the error message which could change in future express versions. There's any other way to catch bodyParser() errors?

但这在我看来是一种非常丑陋的方法,因为我正在比较可能在未来快速版本中更改的错误消息。还有其他方法可以捕获 bodyParser() 错误吗?

EDIT:

编辑:

This is the error when the request body has an invalid json:

这是请求正文包含无效 json 时的错误:

{
  stack: 'Error: invalid json\n    at Object.exports.error (<path>/node_modules/express/node_modules/connect/lib/utils.js:55:13)\n    at IncomingMessage.<anonymous> (<path>/node_modules/express/node_modules/connect/lib/middleware/json.js:74:71)\n    at IncomingMessage.EventEmitter.emit (events.js:92:17)\n    at _stream_readable.js:872:14\n    at process._tickDomainCallback (node.js:459:13)',
  arguments: undefined,
  type: undefined,
  message: 'invalid json',
  status: 400
}

Pretty printed stack:

漂亮的印刷堆栈:

Error: invalid json
    at Object.exports.error (<path>/node_modules/express/node_modules/connect/lib/utils.js:55:13)
    at IncomingMessage.<anonymous> (<path>/node_modules/express/node_modules/connect/lib/middleware/json.js:74:71)
    at IncomingMessage.EventEmitter.emit (events.js:92:17)
    at _stream_readable.js:872:14
    at process._tickDomainCallback (node.js:459:13)

采纳答案by Gabriel Llamas

Ok, found it:

好的,找到了:

bodyParser() is a convenience function for json(), urlencoded() and multipart(). I just need to call to json(), catch the error and call to urlencoded() and multipart().

bodyParser() 是 json()、urlencoded() 和 multipart() 的便捷函数。我只需要调用 json(),捕获错误并调用 urlencoded() 和 multipart()。

bodyParser source

bodyParser 源

app.use (express.json ());
app.use (function (error, req, res, next){
    //Catch json error
    sendError (res, myCustomErrorMessage);
});

app.use (express.urlencoded ());
app.use (express.multipart ());

回答by robertklep

I think your best bet is to check for SyntaxError:

我认为你最好的办法是检查SyntaxError

app.use(function (error, req, res, next) {
  if (error instanceof SyntaxError) {
    sendError(res, myCustomErrorMessage);
  } else {
    next();
  }
});

回答by Daniel Pérez

From the answer of @alexander but with an example of usage

来自@alexander的回答,但有一个用法示例

app.use((req, res, next) => {
    bodyParser.json({
        verify: addRawBody,
    })(req, res, (err) => {
        if (err) {
            console.log(err);
            res.sendStatus(400);
            return;
        }
        next();
    });
});

function addRawBody(req, res, buf, encoding) {
    req.rawBody = buf.toString();
}

回答by Erick Garcia

what I did was just:

我所做的只是:

app.use(bodyParser.json({ limit: '10mb' }))
// body parser error catcher
app.use((err, req, res, next) => {
  if (err) {
    res.status(400).send('error parsing data')
  } else {
    next()
  }
})

回答by dudko

I found checking for SyntaxErrorto be not enough, therefore I do:

我发现检查SyntaxError是不够的,因此我这样做:

if (err instanceof SyntaxError &&
  err.status >= 400 && err.status < 500 &&
  err.message.indexOf('JSON') !== -1) {
    // process filtered exception here
}

回答by Alexander Aleksandrovi? Klimov

(bodyParser, req, res) => new Promise((resolve, reject) => {
    try {
        bodyParser(req, res, err => {
            if (err instanceof Error) {
                reject(err);
            } else {
                resolve();
            }
        });
    } catch (e) {
        reject(e);
    }
})

Bullet-proof. Future-aware. WTFPL-Licensed. And also useful w/ async/await.

防弹。未来意识。WTFPL-许可。并且也很有用,带有异步/等待。