Tôi muốn bắt lỗi từ bodyParser() middleware khi tôi gửi một đối tượng json và nó không hợp lệ vì tôi muốn gửi phản hồi tùy chỉnh thay vì lỗi 400 chung.Catch body bodyParser lỗi
Đây là những gì tôi có và nó hoạt động:
app.use (express.bodyParser());
app.use (function (error, req, res, next){
//Catch bodyParser error
if (error.message === "invalid json"){
sendError (res, myCustomErrorMessage);
}else{
next();
}
});
Nhưng điều này dường như với tôi một cách tiếp cận rất xấu xí vì tôi so sánh các thông báo lỗi mà có thể thay đổi trong các phiên bản rõ ràng trong tương lai. Có cách nào khác để bắt lỗi bodyParser() không?
EDIT:
Đây là lỗi khi cơ thể yêu cầu có json không hợp lệ:
{
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
}
chồng Khá in:
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)
Đó không phải là giải pháp. Bạn không xem xét rằng trước khi mã này có thể là một phần mềm trung gian khác.Nếu bạn nắm bắt theo cách như vậy một số ngoại lệ nó có thể dẫn đến tình trạng không thể đoán trước. Ít nhất thì tốt hơn nên viết: 'app.use (hàm (lỗi, req, res, next) {/ * Nút Shutdown * /}; app.use (bodyParser.json()); app.use (hàm (lỗi, req, res, next) {/ * nếu err.status == 4 ** sau đó xử lý lỗi json => res.status (400) .send(), nút tắt khác * /}); ' – Dao
NGUY HIỂM NGUY HIỂM, điều này bắt bất kỳ lỗi nào trong phần mềm trung gian ở trên, như @Dao đã nói. Không an toàn – light24bulbs