如何将 return 错误从中间件返回给 ExpressJS?

How to return an error back to ExpressJS from middleware?

我正在使用 [Multer][1] 作为中间件来处理多部分表单数据。 Multer 提供了一些配置选项,用于设置文件上传的目的地和名为 diskStorage 的名称。在此区域内,可以进行一些错误检查并控制 Multer 是否授权文件上传。

我的快递路线基本上是这样的:

expressRouter.post(['/create'],
    MulterUpload.single("FileToUpload"), // if this throws an error then have Express return that error to the user
    async function(req, res) {
      // handle the form text fields in req.body here
});

MulterUpload.single() 获取名为“FileToUpload”的文件输入字段并将其发送以执行此操作:

const MulterUpload = multer({
    storage: MulterStorage
)}

const MulterStorage = multer.diskStorage({
    destination: async function (req, file, cb) {
        try {
            if ("postID" in req.body && req.body.postID != null && req.body.postID.toString().length) {

                const Result = await api.verifyPost(req.body.postID)
                if (Result[0].postverified == false) {
                    const Err = new Error("That is not your post!");
                    Err.code = "ILLEGAL_OPERATION";
                    Err.status = 403;
                    throw(Err); // not authorised to upload
                } else {
                    cb(null, '/tmp/my-uploads') // authorised to upload
                }
            }
        } catch (err) {
            // How do I return the err back to Express so it can send it to the user? The err is an unresolved Promise as I am using async/await
        }
    }
    ,
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
    }
})

我似乎无法弄清楚如何将 MulterStorage 中的错误返回给 Express,以便将其作为错误发送回 browser/user。 [1]: https://www.npmjs.com/package/multer

您可以使用错误对象作为第一个参数来调用完成回调。所以,而不是

cb(null, someResult)

您使用错误对象调用回调

cb(new Error("I got a disk error"));

然后,如果您将 multer 设置为普通中间件,这将导致 next(err) 被调用,并且在 Express 中,您的通用错误处理程序将收到错误。

这里有几个例子:

https://www.npmjs.com/package/multer#error-handling

https://github.com/expressjs/multer/issues/336#issuecomment-242906859