Replies: 1 comment 1 reply
-
理论上应该期望:当配置了 |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
在umi4的request源代码中,有这样一段:
const request: IRequest = (url: string, opts: any = { method: 'GET' }) => {
const requestInstance = getRequestInstance();
const config = getConfig();
const { getResponse = false, requestInterceptors, responseInterceptors } = opts;
const requestInterceptorsToEject = requestInterceptors?.map((interceptor) => {
if(interceptor instanceof Array){
return requestInstance.interceptors.request.use((config) => {
const { url } = config;
if(interceptor[0].length === 2){
const { url: newUrl, options } = interceptor[0](url, config);
return { ...options, url: newUrl };
}
return interceptor0;
}, interceptor[1]);
} else {
return requestInstance.interceptors.request.use((config) => {
const { url } = config;
if(interceptor.length === 2){
const { url: newUrl, options } = interceptor(url, config);
return { ...options, url: newUrl };
}
return interceptor(config);
})
}
});
const responseInterceptorsToEject = responseInterceptors?.map((interceptor) => {
return interceptor instanceof Array ?
requestInstance.interceptors.response.use(interceptor[0], interceptor[1]):
requestInstance.interceptors.response.use(interceptor);
});
return new Promise((resolve, reject)=>{
requestInstance
.request({...opts, url})
.then((res)=>{
requestInterceptorsToEject?.forEach((interceptor) => {
requestInstance.interceptors.request.eject(interceptor);
});
responseInterceptorsToEject?.forEach((interceptor) => {
requestInstance.interceptors.response.eject(interceptor);
});
resolve(getResponse ? res : res.data);
})
.catch((error)=>{
requestInterceptorsToEject?.forEach((interceptor) => {
requestInstance.interceptors.request.eject(interceptor);
});
responseInterceptorsToEject?.forEach((interceptor) => {
requestInstance.interceptors.response.eject(interceptor);
});
try {
const handler =
config?.errorConfig?.errorHandler;
if(handler)
handler(error, opts, config);
} catch (e) {
reject(e);
}
reject(error);
})
})
}
它与umi3最大的差异,就是最后有没有统一的异常处理,都会通过reject抛出异常给调用者,如果调用者不catch异常,就会报uncaught error,而在umi3中,是通过skipErrorHandler属性来处理,如果skipErrorHandler=true,则抛给调用都来处理,否则由框架统一处理异常,这样是合理的,而在umi4中,不管有没有统一处理,最后都会reject给调用者,这样是不合理的,不然还要统一异常处理做什么?
其次,umi3中有adapter,在后端返回的参数不满足下面的结构时:
interface ResponseStructure {
success: boolean;
data: any;
errorCode?: number;
errorMessage?: string;
showType?: ErrorShowType;
}
可以重新生成这样的结构,但在umi4中并没有这样的处理逻辑,从代码中可以看出:
requestInstance.interceptors.response.use((response) => {
const { data } = response;
if(data?.success === false && config?.errorConfig?.errorThrower){
config.errorConfig.errorThrower(data);
}
return response;
})
这里的代码要求data是一个ResponseStructure结构,这就意味着我们从后端返回的结构必须是这样,唯一有一个可以处理response的data的地方,是responseInterceptors中,但这里不能修改response,必须原样返回,不然TypeScript会报类型错误,我觉得这些是不太合理的地方
Beta Was this translation helpful? Give feedback.
All reactions