处理上传多个文件时的 multer.single('file') 错误

Handle multer.single('file') error when upload multiple files

我关注了Multer code:

app.post('/profile', upload.single('avatar'), function (req, res, next) {

})

应上传一个文件。但是如果一个人试图上传多个文件,如何捕获错误 MulterError: Unexpected field?

我试过以下但没有成功:

app.post('/profile', upload.single('avatar'), function (req, res, next) {
    try {

    } catch (error) {
    // Why cannot catch any error?
    }
})

upload.single执行next()时,只有它来这里,

app.post('/profile', upload.single('avatar'), function (req, res, next) {
    try {

    } catch (error) {
        // It catches only errors from above `try block`
    }
});

如果 upload.single 遇到任何错误,它不会调用 next() 而是传递给下一个侦听器。要捕获 upload.single 的任何错误,您必须在上面的 app.post(/profile).

之后添加它
app.use(function (err, req, res, next) {
    var error = err.message;
    res.status(500);
    res.send({ "error": error });
});