如何从中间件返回一个错误回ExpressJS ?



我使用[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的错误,以便将其发送回浏览器/用户作为错误。[1]: https://www.npmjs.com/package/multer

可以使用Error对象作为第一个参数来调用完成回调。所以,不用

cb(null, someResult)

用错误对象

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

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

这里有几个例子:

https://www.npmjs.com/package/multer的错误处理https://github.com/expressjs/multer/issues/336 issuecomment - 242906859

相关内容

最新更新