前段时间看了微信小程序的借书系统,看到了这种处理方法。嗯,想着以后也可以在项目中这样实施了。?️一个统一的处理方法,同时针对具体的请求还可以自定义一个异常的处理情况。
let $request = function() {
return new Promise((resolve, reject) => {
let num = Math.random() * 10;
if (num >= 5) {
resolve("simulate normal datas");
} else {
reject("simulate unexpect error");
}
});
};
function $_http(a, b, c) {
return $request().catch(res => {
// 这里做统一处理的报错
console.warn("wo can do sth here such as throw modal alert error");
return Promise.reject("this is the common error ");
});
}
$_http()
.then(data => {
console.log("this is correct steps ");
})
// 这里可以进一步追加各自异常情况的处理
.catch(error => {
console.warn("it is my individual handel error ", error);
// handel error codes
})
.finally(() => {
console.log(
"no matter what status it is you can do sth here eg: tips "
);
});