gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:58:53 25 4
gpt4 key购买 nike

假设我有这样的功能 -

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 block 捕获,并且只有一个通用的 Error 被抛回doSomeOperation 的调用者。

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

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

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

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

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

最佳答案

只需更改行的顺序即可。

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

关于javascript - 抛出自定义错误 async/await try-catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51304601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com