封装一个 JavaScript 异步函数错误处理器
Nathaniel Lin2019年9月12日1 分钟阅读42 次浏览

背景
如果你是一名 JS 开发者,大概早就用上 async 和 await,并且爱不释手了。
再也不用忍受回调地狱(callback hell)或者一长串 .then 链式调用,写异步代码就像写同步程序一样清爽。
直到你撞上了 UnhandledPromiseRejectionWarning 或者 Uncaught (in promise) Error。
于是你开始到处用 try...catch... 把代码包起来,但这样写起来实在太繁琐了。
好消息是,你完全可以自己封装一个通用的异步函数错误处理器:
解决方案
const asyncHandler = fn => async (...args) => {
try {
await fn(...args);
}
catch (err) {
console.log(err);
}
};
它可以接收任意类型、任意参数个数的异步函数。
像这样使用:
const asyncHandler = fn => async (...args) => {
try {
await fn(...args);
}
catch (err) {
console.log(err);
}
};
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const yourFunction = async () => {
await sleep(2000);
throw 'something wrong';
return 'success';
}
(async ()=> {
await yourFunction();
// will cause Uncaught error
await asyncHandler(yourFunction)();
// will handle the error properly
}
)();
处理返回值
当然,如果你需要拿到异步函数的返回结果,只需要顺手把结果 return 出来:
const asyncHandler = fn => async (...args) => {
try {
return await fn(...args);
}
catch (err) {
console.log(err);
}
};
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const yourFunction = async () => {
await sleep(2000);
// throw 'something wrong';
return 'success';
}
(async ()=> {
const result = await asyncHandler(yourFunction)();
//will handle the error properly
console.log(result);
// => 'success'
}
)();
自定义错误处理逻辑
如果你需要做一些定制化的错误处理,比如把它用在 Express.js 里,只要往 catch 块里加上你自己的逻辑就行:
const asyncHandler = fn => async (...args) => {
try {
await fn(...args);
}
catch (err) {
logger.error(err);
const resFn = args.find(arg => arg.name === 'res');
if (resFn) {
let errors = {
message: 'Internal Sever Error',
error: err
};
if (err instanceof mongoose.Error.ValidationError) {
errors = {
message: 'Mongoose Model Validation Error',
error: err
};
}
if (err instanceof mongoose.mongo.MongoError) {
errors = {
message: 'MongDB Error',
error: err
};
}
resFn.status(500).json(errors);
}
} };
之后在 Express 路由里就可以这样用:
router.get('/item',
asyncHandler(async (req, res) => {
// router logic here
}
) )
分享文章
互动