Django rest framework get error message from response during a 400 Bad request

Viewed 1546

I'm currently running a Vue + DRF application. When something in the form is not up to par, and sent to the API, it returns a 400 Bad request as expected. Inspecting the response in the Network tab you get a clear validation error message, such as {"zip_code":["This field must not be blank"]}.

The question is, how can i extract this and display it in my Vue application? Trying to catch the error just returns Uncaught (in promise) Error: Request failed with status code 400 at eval instead of the actual error message ("This field must not be blank").

The code patching looks something like:

axios.patch(`users/${this.$route.params.id}/`, this.user)
    .then(...)
    .catch(error => {...}) // get error message and display it frontend to user 
1 Answers

If anyone else has the same problem: using axios, you can get the error response body through .catch(error => { console.log(error.response.data) }.

Related