如何正确处理axios错误以及如何获取详细的错误描述?

dev*_*mat 2 javascript reactjs axios

我有一个关于 axios 和错误处理的问题。这就是我在用户从前端登录时用来处理错误的方法:

    axios.post('http://localhost:3001/login',
        {
            login: user.login,
            password: user.password,
        }
    )
    .then(
        (response) => {
            // code
        },
        (error) => {
            // error handling
        }
    );
Run Code Online (Sandbox Code Playgroud)

这是第二种方法:

    axios.post('http://localhost:3001/login',
        {
            login: user.login,
            password: user.password,
        }
    )
    .then(
        (response) => {
            // code
        }
    ).catch((error) => {
        // error handling
    });
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?是一样的吗?当服务器无法访问时,错误消息相同:“网络错误”。有什么办法可以得到更详细的错误信息吗?(例如在控制台中我收到 CORS 错误)

Kar*_*k R 8

该错误可能发生在不同部分 - 请求、响应。

当没有响应时,就会出现请求错误。像 404 等,没有默认响应。

当 API 发送自定义响应来处理错误时,就会出现响应错误。

我以前是这样处理的:

const handleErrorResponse = (error) => {
  let errorResponse;
  if(error.response && error.response.data) {
    // I expect the API to handle error responses in valid format
    errorResponse = error.response.data;
    // JSON stringify if you need the json and use it later
  } else if(error.request) {
    // TO Handle the default error response for Network failure or 404 etc.,
    errorResponse = error.request.message || error.request.statusText;
  } else {
    errorResponse = error.message;
  }
  throw new Error(errorResponse);
}
Run Code Online (Sandbox Code Playgroud)

现在,

axios.get(/foo/bar)
.then(res => doSOmething())
.catch(err => handleErrorResponse(err))
Run Code Online (Sandbox Code Playgroud)

我使用错误处理作为字符串的错误响应。如果需要的话,您也可以将它与 axios 拦截器一起使用。