简体   繁体   English

使用try和catch语句处理异步HTTP错误

[英]Handle async http error with try and catch statement

I hope this is an easy one: 我希望这是一个简单的方法:

I am trying to implement error handling within a try and catch statement in a ReactJS action creator. 我正在尝试在ReactJS动作创建器的try和catch语句中实现错误处理。

export const getUserKitchens = () => async dispatch => {
    try{
        const response = await axios.get(
            `${baseURL}customer/get-user-kitchens/`,
         )
        dispatch({type:LOAD_USER_KITCHENS, payload: response.data})
    } catch(e) {
        const msg = "something"
        dispatch(displayStatus(msg, true))
    }
}

If the request fails with an HTTP status of 401 I want to log out the user. 如果请求失败且HTTP状态为401,我想注销该用户。 Therefore, I need to have access to the Http response headers from the catch statement and retrieve the HTTP status from there. 因此,我需要可以从catch语句访问Http响应标头,并从那里检索HTTP状态。

Is this possible? 这可能吗?

According to await MDN docs 根据await MDN docs

The await expression causes async function execution to pause until a Promise is resolved, that is fulfilled or rejected, and to resume execution of the async function after fulfillment. 等待表达式使异步功能的执行暂停,直到解决了Promise(被实现或被拒绝),并在实现后恢复执行异步功能。 When resumed, the value of the await expression is that of the fulfilled Promise. 恢复后,await表达式的值就是已实现的Promise的值。

If the Promise is rejected, the await expression throws the rejected value. 如果Promise被拒绝,则await表达式将抛出被拒绝的值。

So if there is an API error, the error object is being throws which you get in the catch block and can access the status and headers from it with error.response.status and error.response.headers 因此,如果发生API错误,则会抛出错误对象,您可以在catch块中获得该对象,并可以使用error.response.statuserror.response.headers访问状态和标头

export const getUserKitchens = () => async dispatch => {
    try{
        const response = await axios.get(
            `${baseURL}customer/get-user-kitchens/`,
         )
        dispatch({type:LOAD_USER_KITCHENS, payload: response.data})
    } catch(e) {
        const status = e.response.status;
        dispatch(displayStatus(status, true))
    }
}

The e object in the catch statement is an error object. catch语句中的e对象是错误对象。 You could access the status code with error.response.status and the headers with error.response.headers . 你可以访问与状态代码error.response.status并用头error.response.headers Something like this should be useful: 这样的事情应该有用:

export const getUserKitchens = () => async dispatch => {
    try{
        const response = await axios.get(
            `${baseURL}customer/get-user-kitchens/`,
         )
        dispatch({type:LOAD_USER_KITCHENS, payload: response.data})
    } catch(e) {
        const status = e.response.status;
        if (status === 401) {
           dispatch({type:LOG_USER_OUT}) //LOG_USER_OUT is a logout action
        } else {
          dispatch(displayStatus(status, true))
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM