Search code examples
reactjsreduxaxios

axios catch doesn't catch error


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.


Solution

  • 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>