如何捕获async函数中异步操作抛出的错误

421 阅读1分钟

下面代码来源项目中使用的一个第三方库await-to-js, github 1.6k stars。原始版本是 typescript 编写,线面是编译后的 javascript 版本。

function to(promise, errorExt) {
    return promise
        .then(function (data) { return [null, data]; })["catch"](function (err) {
            if (errorExt) {
                Object.assign(err, errorExt);
            }
            return [err, undefined];
        });
}

使用:

const errorFuc = async () => {
    const [ error, result ] = await to(new Promise(res => setTimeout(res("success"), 100)));
    console.log(error,result);
    // do something with result;
}

使用 async...await 函数时需要处理对 异步函数的错误进行捕获,捕获方法一般有两种,一是直接在异步函数中进行捕获,而是在try...catch...结构中进行捕获。

直接捕获异步操作的错误:

const errorFunc = async () => {
    const error = await new Promise((res,rej) => setTimeout(rej("error"), 1000)).catch(error => error);
	console.log(error);
    // do something with error;  
    return error;     
}

使用 try...catch...捕获异步错误:

const errorFunc = async () => {
    try {
        const error = await new Promise((res,rej) => setTimeout(rej("error"), 1000))
    } catch (error) {
        console.log(error);
    	// do something with error;  
    }  
}

await-to-js 比较可采用的一点是将异步操作的正确返回值和错误封装起来,看起来、使用起来很简洁。