Z. M.
Z. M.

Reputation: 389

How to check for specific backend error keys when using async/await?

I want to display a custom message in Vue (with Django as the backend) when creating an account if the entered email already exists in the database.

Currently the server returns a 400 with the following response: {"email":["There is another user with this email"]}

How can I access this error object to check if it contains an "email" key?

I've found this approach creating a wrapper: https://dev.to/sadarshannaiynar/capture-error-and-data-in-async-await-without-try-catch-1no2 but I feel like there must be a better/simpler way of handling this

Things I tried:

1) const { error, data } = await usersAPI.create(userData) where "create" is:

create (data) { return Vue.axios.post(url, data, config) } then console.error(error) (but it doesn't print anything)

2) Using try-catch(error) - prints nothing

3) Appending catch(e => console.error(e) to the await call - still nothing

Upvotes: 0

Views: 88

Answers (1)

ManUtopiK
ManUtopiK

Reputation: 4714

Axios return an object error, you can get the content with error.message.

axios.post('/badurl')
.then(response => { 
	console.log(response)
})
.catch(error => {
    console.log(error.message)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>

Upvotes: 1

Related Questions