1、在中,统一处理接口错误信息弹框提示
在开发中经常会遇到文件在上传、下载后端接口有时候会返回非文件流的错误信息,需要进行弹框提示,我们统一放到文件中在响应拦截器里进行处理
// 响应拦截器
service.interceptors.response.use( async res => {
// 这一步就是进行错误弹框处理,
const isBlob = res.data instanceof Blob;
if(isBlob) {
const blobObj = await BlobToObject(res.data);
if(blobObj?.errCode) {
res = blobObj;
Message({
message: blobObj.errMsg,
type: 'error'
});
}
}
)
function BlobToObject (blob) {
return new Promise((resolve, reject) => {
try {
const { type } = blob;
if (type === 'application/json') {
const file = new FileReader();
let json = {};
file.readAsText(blob, 'utf-8');
file.onload = function () {
json = JSON.parse(file.result);
resolve(json);
};
} else {
resolve({});
}
} catch (err) {
resolve({ err });
}
});
}
``
2、这里面需要注意的点是:
1、需要在顶部用 import { Notification, MessageBox, Message } from ‘element-ui’,将需要用到的弹框MessageBox或Message 引入否则无法触发弹框效果;
2、const isBlob = instanceof Blob;根据个人项目是res还是,包括调用BlobToObject()方法
3、弹框提示根据接口返回是否是code(我的项目是errCode,错误信息是errMsg)