[英]How to return an error back to ExpressJS from middleware?
我使用 [Multer][1] 作為中間件來處理多部分表單數據。 Multer 提供了一些配置選項來設置文件上傳的目的地和名為diskStorage
的名稱。 正是在這個區域內,人們可以進行一些錯誤檢查並控制 Multer 是否授權文件上傳。
我的 Express 路線基本上是這樣的:
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
您可以使用錯誤 object 作為第一個參數來調用完成回調。 所以,而不是
cb(null, someResult)
您調用回調時出現錯誤 object
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.