【发布时间】:2019-05-11 06:30:41
【问题描述】:
当请求中未指定文件时,我使用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
}
}
有没有其他方法来处理这种错误情况?
【问题讨论】:
-
如果你想抛出异常,为什么要把它放在 try catch 中——当然,如果你没有文件,那么应该抛出异常并且程序在那时退出?这样,任何调用该服务的人都会知道发生了错误(而不是默默地吞下它)
标签: javascript node.js typescript error-handling try-catch