api错误401不能使用axios捕获

问题描述 投票:0回答:1

我有一个正在使用的应用程序。

我设置了redux-obsrrvableaxios-observable

我的请求未经授权时遇到问题。

使用以下代码=>

const getWorkspaces = (action$, state$) => action$.pipe(
    ofType(WorkspaceActions.getWorkspacesRequest),
    switchMap(action =>
        HttpService.GetAsync<any>('get_all_workspaces').pipe(
            map(response => {
                console.log(response)
                let data = response.data ? response.data : [];
                return of(WorkspaceActions.getWorkspacesSuccess(data));
            }),
            catchError((error: string) => {
                console.log(error)
                return of(WorkspaceActions.getWorkspacesFailed({error}));
            })
        )
    )
);

api返回错误401,但是redux效果进入映射内,而不是catchError内。我认为错误401是考虑者错误,应进入catchError。

我使用错误的东西吗?

编辑:

我已经设置了以下内容

Axios.interceptors.response.use(response => {
    console.log(`[response] --> ${response.status}`)
    return response;
}, error => {
    if(error && error.response) {
                console.log(error.response)
                console.log(`[error][code: ${error.response.status}] -->> ${error.response}`);
    }
    return error;
})

并且这里确实会出现错误,但是在我使用时是一个

class HttpService {

    // apicoreBaseUrl define apicore base url from env
    private static apicoreBaseUrl = (targetApi: string, basePath: string = "hexacloud"): string => {
        return `/${basePath}/${targetApi}`
    }

    // Get common http get function
    public static GetAsync<T>(targetApi: string, params?: any, basePath?: string): AxiosObservable<T> {
        return Axios.get(this.apicoreBaseUrl(targetApi, basePath), { params: params })
    }

    public static PostAsync<T>(targetApi: string, data: any, basePath?: string): AxiosObservable<T> {
        return Axios.post(this.apicoreBaseUrl(targetApi, basePath), data);
    }
}

返回者可观察到的不抓住

reactjs axios observable redux-observable
1个回答
0
投票

使用拦截器来处理401错误

axios.interceptors.response.use(response => {
   return response;
}, error => {
  if (error.response.status === 401) {
   //place your reentry code
  }
  return error;
});

也请阅读此链接,它将对您有帮助:How to handle 401 (Authentication Error) in axios and react?

© www.soinside.com 2019 - 2024. All rights reserved.