首页 文章

抛出错误并使用finally块发送错误代码500

提问于
浏览
0

我在请求中未指定文件时使用 throwExecption ,在我的功能结束时,我使用 finally block来取消链接文件 .

所以我的情况 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
  }
}

还有另一种方法可以处理这种错误吗?

1 回答

  • 2

    您可以在try / catch块之外移动if块

    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
    }
    

相关问题