【问题标题】:Throw custom errors async/await try-catch抛出自定义错误异步/等待 try-catch
【发布时间】:2018-12-20 14:57:53
【问题描述】:

假设我有这样的功能 -

doSomeOperation = async () => {
  try {
    let result = await DoSomething.mightCauseException();
    if (result.invalidState) {
      throw new Error("Invalid State error");
    }

    return result;
  } catch (error) {
    ExceptionLogger.log(error);
    throw new Error("Error performing operation");
  }
};

这里的DoSomething.mightCauseException 是一个可能导致异常的异步调用,我使用try..catch 来处理它。但是使用得到的结果,我可能会决定我需要告诉doSomeOperation的调用者操作由于某种原因而失败。

在上面的函数中,我抛出的Error 被catch 块捕获,只有一个通用的Error 被抛出给doSomeOperation 的调用者。

doSomeOperation 的调用者可能正在做这样的事情 -

doSomeOperation()
  .then((result) => console.log("Success"))
  .catch((error) => console.log("Failed", error.message))

我的自定义错误永远不会出现在这里。

在构建 Express 应用时可以使用此模式。路由处理程序会调用一些可能希望以不同方式失败的函数,并让客户端知道失败的原因。

我想知道如何做到这一点?这里还有其他模式可以遵循吗?谢谢!

【问题讨论】:

  • 从您的mightCauseException 中投掷。这将冒泡到您的 catch 块中并被扔到那里。

标签: javascript error-handling async-await


【解决方案1】:

只需更改行的顺序即可。

doSomeOperation = async() => {
    let result = false;
    try {
        result = await DoSomething.mightCauseException();
    } catch (error) {
        ExceptionLogger.log(error);
        throw new Error("Error performing operation");
    }
    if (!result || result.invalidState) {
        throw new Error("Invalid State error");
    }
    return result;
};

更新 1

或者您可以创建如下自定义错误。

class MyError extends Error {
  constructor(m) {
    super(m);
  }
}

function x() {
  try {
    throw new MyError("Wasted");
  } catch (err) {
    if (err instanceof MyError) {
      throw err;
    } else {
      throw new Error("Bummer");
    }
  }

}

x();

更新 2

将此映射到您的案例,

class MyError extends Error {
  constructor(m) {
    super(m);
  }
}

doSomeOperation = async() => {
  try {
    let result = await mightCauseException();
    if (result.invalidState) {
      throw new MyError("Invalid State error");
    }

    return result;
  } catch (error) {
    if (error instanceof MyError) {
      throw error;
    }
    throw new Error("Error performing operation");
  }
};

async function mightCauseException() {
  let random = Math.floor(Math.random() * 1000);
  if (random % 3 === 0) {
    return {
      invalidState: true
    }
  } else if (random % 3 === 1) {
    return {
      invalidState: false
    }
  } else {
    throw Error("Error from function");
  }
}


doSomeOperation()
  .then((result) => console.log("Success"))
  .catch((error) => console.log("Failed", error.message))

【讨论】:

  • 自定义错误解决方案是我想到的。但我不喜欢创建它们的开销。但这是我想的最干净的方式。感谢您理解我的问题@chatura :)
【解决方案2】:

您可以简单地使用throw 而不是使用Error 构造函数

const doSomeOperation = async () => {
  try {
      throw {customError:"just throw only "}
  } catch (error) {
    console.log(error)
  }
};

doSomeOperation()

【讨论】:

    猜你喜欢
    • 2019-02-11
    • 2021-01-12
    • 1970-01-01
    • 2016-01-26
    • 2020-03-08
    • 1970-01-01
    相关资源
    最近更新 更多