Reputation: 7003
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.
Upvotes: 12
Views: 26152
Reputation: 622
In my case (axios 0.27.2), 400 responses are indeed handled as errors by axios.
This problem could happen due to a badly written response interceptor which doesn't return Promise.reject in unhandled cases.
axios.interceptors.response.use(
(response) => response,
(error) => {
if (condition) {
// Handle error
} else {
// This is important, so that unhandled cases make axios throw errors
return Promise.reject(error);
}
}
);
Upvotes: 14
Reputation: 62881
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>
Upvotes: 5
Reputation: 24680
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 }) } )
Upvotes: 6