尝试抓住 - 重新抛出 - 正确的模式

时间:2018-01-24 17:41:15

标签: javascript try-catch

如果我有这样的代码:

let result;
try {
    result = doSomethingThatCanThrow();
} catch (e) {
    throw new Error(`Thrown error because <some info> ${e}`)
}

// do something with result if didn't throw

这是JS中的有效模式吗?我不喜欢使用let。我更喜欢const但我不能在这种情况下使用它,因为它不会在try-catch块之外可用。

我可以将整个代码放在try块中并删除let但是在我看来它会更难阅读:

try {
    const result = doSomethingThatCanThrow();
    // do something with result if didn't throw
} catch (e) {
    throw new Error(`Thrown error because <some info> ${e}`)
}

请记住,它总能增长。

此外,我总是可以跳过重新抛出,但我想为错误添加更多信息。

哪个选项更好,为什么?还有其他可能性吗?

3 个答案:

答案 0 :(得分:0)

您可以使用finally

(async(doSomethingThatCanThrow) => {

  let result;
  try {
    result = await doSomethingThatCanThrow();
  } catch (e) {
    throw new Error(`Thrown error because <some info> ${e}`)
  } finally {
    if (result !== undefined) {
      // do something with result if didn't throw
      console.log(result);
    } else {
      console.log(result);
    }
  }
  // do stuff 
})(() => Promise.reject(123))
.catch(err => console.error(err));

答案 1 :(得分:0)

尝试测试条件,看看变量结果是否为空!

&#13;
&#13;
var result
try {
    result = "This time it worked!";
} catch (e) {
    throw new Error(`Thrown error because <some info> ${e}`)
}

if (result) {
    console.log(result)
}
&#13;
&#13;
&#13;

&#13;
&#13;
var result
try {

} catch (e) {
  }

// do something with result if didn't throw

if (!result) {
    // var result undefined
    // Result not thrown!
    console.log("Failed")
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

在这种情况下,我认为避免let的唯一真实方法(除了建议使用var作为其他响应,否则不要这样做)是将try-catch提取到函数中并返回直接用try块得到结果,即

const doSomethingThatCanThrowAndRethrowWithUpdatedMessageIfFails = () => {
  try {
    return doSomethingThatCanThrow();
  } catch (e) {
    throw new Error(`Thrown error because <some info> ${e}`);
  }
}

const result = doSomethingThatCanThrowAndRethrowWithUpdatedMessageIfFails();