【问题标题】:throw error and use finally block sends error code 500抛出错误并使用 finally 块发送错误代码 500
【发布时间】: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


【解决方案1】:

您可以将 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多