简体   繁体   English

抛出自定义错误async / await try-catch

[英]Throw custom errors async/await try-catch

Let's say I have a function like this - 假设我有这样的功能 -

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");
  }
};

Here the DoSomething.mightCauseException is an asynchronous call that might cause an exception and I'm using try..catch to handle it. 这里的DoSomething.mightCauseException是一个异步调用,可能会导致异常,我正在使用try..catch来处理它。 But then using the result obtained, I might decide that I need to tell the caller of doSomeOperation that the operation has failed with a certain reason. 但是然后使用获得的结果,我可能会决定我需要告诉调用者doSomeOperation操作因某种原因而失败。

In the above function, the Error I'm throwing is caught by the catch block and only a generic Error gets thrown back to the caller of doSomeOperation . 在上面的函数中,我正在抛出的Errorcatchcatch ,只有一个普通的Error被抛回到doSomeOperation的调用者。

Caller of doSomeOperation might be doing something like this - doSomeOperation调用者可能会做这样的事情 -

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

My custom error never gets here. 我的自定义错误永远不会到达。

This pattern can be used when building Express apps. 构建Express应用程序时可以使用此模式。 The route handler would call some function which might want to fail in different ways and let the client know why it failed. 路由处理程序将调用某些可能希望以不同方式失败的函数,并让客户端知道它失败的原因。

I'm wondering how this can be done? 我想知道如何做到这一点? Is there any other pattern to follow here? 这里还有其他模式吗? Thanks! 谢谢!

Just change the order of your lines. 只需更改行的顺序即可。

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;
};

Update 1 更新1

Or you could create custom errors as below. 或者您可以创建自定义错误,如下所示。

 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(); 

Update 2 更新2

Mapping this to your case, 将此映射到您的案例,

 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)) 

You can simply use throw instead of using Error constructor 您可以简单地使用throw而不是使用Error构造函数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM