异步/等待中抛出自定义错误的尝试-捕获

3

假设我有一个这样的函数 -

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 操作已因某些原因失败。
在上面的函数中,我抛出的 Errorcatch 块捕获,然后只会向 doSomeOperation 的调用者抛出通用的 ErrordoSomeOperation 的调用者可能会像这样做 -
doSomeOperation()
  .then((result) => console.log("Success"))
  .catch((error) => console.log("Failed", error.message))

我的自定义错误从未到达这里。

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

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


mightCauseException 中抛出异常。这将传递到 catch 块并在那里抛出。 - James Gould
2个回答

2
只需要改变你的代码行顺序。
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 :) - Steve Robinson

0

在编程中,你可以直接使用throw而不是使用Error构造函数。

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

doSomeOperation()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接