Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 366
Xeen Avatar asked Nov 06 '17 21:11

Xeen


2 Answers

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 }) } )
like image 91
bennygenel Avatar answered Sep 28 '22 01:09

bennygenel


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>
like image 29
Brett DeWoody Avatar answered Sep 28 '22 03:09

Brett DeWoody