axios catch doesn't catch error

会有一股神秘感。 提交于 2020-05-30 07:56:31

问题


I'm using axios 0.17.0 with the following code:

this.props.userSignupRequest(this.state)
  .then( res => { console.log(res.data) } )
  .catch( err => { this.setState({ errors: err.response }) } )

And the server is set to return a 400 when user signup validation doesn't pass. That also shows up in console: POST 400 (Bad Request), but the setState is not being executed. Why is that? I also tried console.log(err) and nothing.


回答1:


A few issues could be at play, we'll likely need to see more of your code to know for sure.

Axios 0.17.0 will throw an error on the 400 response status. The demo below shows this.

The unexpected behavior could be due to the asynchronous behavior of setState(). If you're trying to console.log the state immediately after calling setState() that won't work. You'll need to use the setState callback.

const signinRequest = () => {
  return axios.post('https://httpbin.org/status/400');
}   
  
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      errors: null
    }
  }
  
  handleSignin = () => {
    this.props.userSigninRequest()
      .then(result => {
        console.log(result.status);
      })
      .catch(error => {
        this.setState({
          errors: error.response.status
        }, () => {
          console.error(this.state.errors);
        });
      });
  }
  
  render() {
    return (
      <div>
         <button onClick={this.handleSignin}>Signin</button>
        {this.state.errors}
      </div>
    )
  }
}

ReactDOM.render(<App userSigninRequest={signinRequest} />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.0/axios.js"></script>

<div id="app"></div>



回答2:


POST 400 (Bad Request) is not an error, it is a not successful response. catch fires when there is an error on request.

If you want to catch 400 or similar HTTP errors you need to check status

Example

this.props.userSignupRequest(this.state)
  .then( res => { console.log(res.status) } )
  .catch( err => { this.setState({ errors: err.response }) } )


来源:https://stackoverflow.com/questions/47146121/axios-catch-doesnt-catch-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!