[英]throw error and use finally block sends error code 500
當未在請求中指定文件時,我正在使用throwExecption
,在功能結束時,我使用了finally
塊來取消鏈接文件。
因此,如果未指定file
我應該得到400條帶錯誤消息的代碼。
但是由於finally
塊throw Execption
被它覆蓋
try {
if (!file) {
throw new BadRequestException('no file');
}
}
...
finally {
// On error or not : delete temporary file
await fse.unlink(file.path); // error 500 because Cannot read property 'path' of undefined
}
我已經找到一種解決方法,如果要檢查finally
塊中的文件,但這會使代碼變得多余。
try {
if (!file) {
throw new BadRequestException('no file');
}
}
...
finally {
// On error or not : delete temporary file
if (file) {
await fse.unlink(file.path);
} else {
throw new BadRequestException('no file'); <== redundancy
}
}
還有另一種方法來處理這種錯誤情況嗎?
您可以將if塊移到try / catch塊之外
if (!file) { try { ...your block of code } ... finally { // On error or not : delete temporary file await fse.unlink(file.path); } } else { throw new BadRequestException('no file'); <= = redundancy }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.