1
votes

I am making a request using vue + axios. Usually like this:

axios.get('/url').then(response => {} ).catch(error => {})

This will catch the response if the HTTP response was not 404, but if it was 404 it would be caught inside the catch.

But sometimes I want the response to be treated as an error. For example, if GET /user response 200 OK, but no users in the data, how do I make that response be transferred into the catch block?

Is it possible to do that with axios, or does it only return response/error based on the HTTP status code?

3
The data validation and 404 HTTP Response should be happening server-side. And if it's truly bad data, then it should be more along the lines of a 400 Bad Request response. - Reed

3 Answers

2
votes

You can throw an error to have your answer treated by the catch block:

axios.get('/url').then(response => {
    if (/* you're not satisfied with the response*/) {
         throw new Error("I'm not satisfied");
    }
}).catch(error => {})
1
votes

That Should happen on your server. The server that is handling the request should return a 404 response error in case there was no users.

1
votes

You can always use the fact that in JavaScript you can share behavior using function.

function handleError (error) { ... };

axios.get('/url').then(response => { 
    if( "some condition" ) {
       handleError("Some unmet condition");
    }  
).catch(handleError);