Can I throw error in axios post based on response status - javascript

Is it possible to throw an error on purpose inside the .then() block in axios? For instance, if the api responds with 204 status code, could I throw an error and run the catch block?
For example:
axios.post('link-to-my-post-service', {
json-input
}).then(response => {
if (response.status === 200) {
//proceed...
}
else {
// throw error and go to catch block
}
}).catch(error => {
//run this code always when status!==200
});
EDIT
I tried this, but it didn't work:
var instance = axios.create({
validateStatus: function (status)
{
return status == 200;
}
});
axios.post('link-to-my-post-service', {input: myInput}, instance)
.then(response => {
dispatch({
type: "FETCH_SUCCESS",
payload: response.data
});
}).catch(error => {
dispatch({
type: "FETCH_FAILED",
payload: error
});
});
When I get a status code 204, still the executed block is then() block instead of the catch block.
EDIT 2
The correct answer using Ilario's suggestion is this:
var instance = axios.create({
validateStatus: function (status)
{
return status == 200;
}
});
instance.post('link-to-my-post-service', {input: myInput})
.then(response => {
dispatch({
type: "FETCH_SUCCESS",
payload: response.data
});
}).catch(error => {
dispatch({
type: "FETCH_FAILED",
payload: error
});
});
Now when the status code is not equal to 200 the catch block code is executed.

If you give a look at the GitHub Project Page you will notice following option description.
/* `validateStatus` defines whether to resolve or reject the promise for a given
* HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
* or `undefined`), the promise will be resolved; otherwise, the promise will be
*/ rejected.
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
So you could create an Instance with your own configuration.
var instance = axios.create({
validateStatus: function (status) {
return status == 200;
},
});
You could also set defaults. These will be applied to every request.
axios.defaults.validateStatus = () => {
return status == 200;
};
UPDATE 1
To set the config only on a specific operation you could replace "config" with your desired values or methods.
axios.post(url[, data[, config]])
UPDATE 2
I tried this, but it didn't work.
You cannot pass the instance to axios.post(). You must call post on the new instance.
var instance = axios.create({
validateStatus: function (status) {
return status == 200;
}
});
instance.post('url', data, config);

Thank you very much for your suggestions. The answer was simpler than I expected.
I didn't want to set any default options to change the behavior of axios, so I just tried something like the code below, and it worked. Every time the code throw new Error("Error"); is executed, the catch block code is executed after that.
axios.post('link-to-my-post-service', {
json-input
}).then(response => {
if (response.status === 200) {
//proceed...
}
else {
// throw error and go to catch block
throw new Error("Error");
}
}).catch(error => {
//when throw "Error" is executed it runs the catch block code
console.log(error)
});

Related

Handling status 500 with try and catch

I can't tell what is the optimal way to handle the status 500 sent by my API. Could you please help me?
In the case below, when my API responds with a status 500, I wish to set an error message in my redux store. When my API sent a successful status code, I wish to "Fetch the user decks" in my store.
My first attempt felt logical and dry to me, but it did not work:
const createDeck = async () => {
try {
const request = await fetch(`${back}/deck/`, options)
const response = await request.json()
store.dispatch({ type: FETCH_USER_DECKS })
} catch (error) {
store.dispatch({ type: SET_ERROR, message: error })
}
}
When the API send a 500 status, no exception seems to be thrown and the code in my catch block is ignored.
My second and third attempt worked as I excepted them too, but they feel convoluted and weird:
2nd attempt:
const createDeck = async () => {
try {
const request = await fetch(`${back}/deck/`, options)
const response = await request.json()
if (request.status === 201 || request.status === 200) {
store.dispatch({ type: FETCH_USER_DECKS })
} else {
store.dispatch({ type: SET_ERROR, message: error })
}
} catch (error) {
console.log('error')
}
}
This works, but it ignores completely the catch block, making me wonder: what's even the point of try...catch then?
Third attempt:
const createDeck = async () => {
try {
const request = await fetch(`${back}/deck/`, options)
const response = await request.json()
if (request.status === 201 || request.status === 200) {
store.dispatch({ type: FETCH_USER_DECKS })
} else {
throw response
}
} catch (error) {
store.dispatch({ type: SET_ERROR, message: error })
}
}
This third attempt make use of catch, but it feels weird to manually throw an exception, to be immediately caught by catch.
Am I missing something here?
Isbn has properly answered this in the comments. I'm putting it here again for visibility:
"Since you're using fetch() it would probably make sense to adopt its implementation model and to not consider a 500 response as an exception (attempt 2). But I wouldn't see anything wrong with your third attempt either (axios, for example, would raise an error in that case). Note that fetch() response exposes a ok property to check whether the request succeeded or not"

axios: how to access response when getting 403 exception? [duplicate]

This may seem stupid, but I'm trying to get the error data when a request fails in Axios.
axios
.get('foo.example')
.then((response) => {})
.catch((error) => {
console.log(error); //Logs a string: Error: Request failed with status code 404
});
Instead of the string, is it possible to get an object with perhaps the status code and content? For example:
Object = {status: 404, reason: 'Not found', body: '404 Not found'}
What you see is the string returned by the toString method of the error object. (error is not a string.)
If a response has been received from the server, the error object will contain the response property:
axios.get('/foo')
.catch(function (error) {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
});
With TypeScript, it is easy to find what you want with the right type.
This makes everything easier because you can get all the properties of the type with autocomplete, so you can know the proper structure of your response and error.
import { AxiosResponse, AxiosError } from 'axios'
axios.get('foo.example')
.then((response: AxiosResponse) => {
// Handle response
})
.catch((reason: AxiosError) => {
if (reason.response!.status === 400) {
// Handle 400
} else {
// Handle else
}
console.log(reason.message)
})
Also, you can pass a parameter to both types to tell what are you expecting inside response.data like so:
import { AxiosResponse, AxiosError } from 'axios'
axios.get('foo.example')
.then((response: AxiosResponse<{user:{name:string}}>) => {
// Handle response
})
.catch((reason: AxiosError<{additionalInfo:string}>) => {
if (reason.response!.status === 400) {
// Handle 400
} else {
// Handle else
}
console.log(reason.message)
})
As #Nick said, the results you see when you console.log a JavaScript Error object depend on the exact implementation of console.log, which varies and (imo) makes checking errors incredibly annoying.
If you'd like to see the full Error object and all the information it carries bypassing the toString() method, you could just use JSON.stringify:
axios.get('/foo')
.catch(function (error) {
console.log(JSON.stringify(error))
});
There is a new option called validateStatus in request config. You can use it to specify to not throw exceptions if status < 100 or status > 300 (default behavior). Example:
const {status} = axios.get('foo.example', {validateStatus: () => true})
You can use the spread operator (...) to force it into a new object like this:
axios.get('foo.example')
.then((response) => {})
.catch((error) => {
console.log({...error})
})
Be aware: this will not be an instance of Error.
I am using this interceptors to get the error response.
const HttpClient = axios.create({
baseURL: env.baseUrl,
});
HttpClient.interceptors.response.use((response) => {
return response;
}, (error) => {
return Promise.resolve({ error });
});
In order to get the http status code returned from the server, you can add validateStatus: status => true to axios options:
axios({
method: 'POST',
url: 'http://localhost:3001/users/login',
data: { username, password },
validateStatus: () => true
}).then(res => {
console.log(res.status);
});
This way, every http response resolves the promise returned from axios.
https://github.com/axios/axios#handling-errors
Whole error can only be shown using error.response like that :
axios.get('url').catch((error) => {
if (error.response) {
console.log(error.response);
}
});
const handleSubmit = (e) => {
e.preventDefault();
// console.log(name);
setLoading(true);
createCategory({ name }, user.token)
.then((res) => {
// console.log("res",res);
setLoading(false);
setName("");
toast.success(`"${res.data.name}" is created`);
loadCategories();
})
.catch((err) => {
console.log(err);
setLoading(false);
if (err.response.status === 400) toast.error(err.response.data);//explained in GD
});
};
See the console log then you will understand clearly
With Axios
post('/stores', body).then((res) => {
notifyInfo("Store Created Successfully")
GetStore()
}).catch(function (error) {
if (error.status === 409) {
notifyError("Duplicate Location ID, Please Add another one")
} else {
notifyError(error.data.detail)
}
})
It's indeed pretty weird that fetching only error does not return an object. While returning error.response gives you access to most feedback stuff you need.
I ended up using this:
axios.get(...).catch( error => { return Promise.reject(error.response.data.error); });
Which gives strictly the stuff I need: status code (404) and the text-message of the error.
Axios. get('foo.example')
.then((response) => {})
.catch((error) => {
if(error. response){
console.log(error. response. data)
console.log(error. response. status);
}
})
This is a known bug, try to use "axios": "0.13.1"
https://github.com/mzabriskie/axios/issues/378
I had the same problem so I ended up using "axios": "0.12.0". It works fine for me.
You can put the error into an object and log the object, like this:
axios.get('foo.example')
.then((response) => {})
.catch((error) => {
console.log({error}) // this will log an empty object with an error property
});
It's my code: Work for me
var jsonData = request.body;
var jsonParsed = JSON.parse(JSON.stringify(jsonData));
// message_body = {
// "phone": "5511995001920",
// "body": "WhatsApp API on chat-api.com works good"
// }
axios.post(whatsapp_url, jsonParsed,validateStatus = true)
.then((res) => {
// console.log(`statusCode: ${res.statusCode}`)
console.log(res.data)
console.log(res.status);
// var jsonData = res.body;
// var jsonParsed = JSON.parse(JSON.stringify(jsonData));
response.json("ok")
})
.catch((error) => {
console.error(error)
response.json("error")
})

Axios override, get status code from the data response instead of status

I'm calling an API that defines the statusCode from data instead of the response code:
{
data: {
statusCode: 422,
message: "User's not found"
},
status: 200
}
In my axios get request it's getting the status code from the status instead in data.
return axios.get(`${process.env.BASE_URL}/users`)
.then(response => {
console.log(response);
}).catch(err => {
console.log(err.message);
});
I'm getting the response but it should go to catch since it's 422.
How can I refer to the statusCode of the data response so that if it's not 200 it should go to catch statement
You can intercept the response, inspect the data and throw a custom error in this case:
// Add a response interceptor
axios.interceptors.response.use(function(response) {
if (response.data && response.data.statusCode && !(response.data.statusCode >= 200 && response.data.statusCode < 300)) throw new Error()
return response;
}, function(error) {
return Promise.reject(error);
});
// Make a GET request
axios.get(url)
.then((data) => {
console.log('data', data)
})
.catch((e) => {
console.log('error', e)
})
This way you configure your axios instance so you dont have to repeat yourself for every single request in your app
Also, you can override the status using following code. But since status validation has already executed, it will not throw errors on bad status codes
// Add a response interceptor
axios.interceptors.response.use(function(response) {
if (response.data && response.data.statusCode) response.status = response.data.statusCode
return response;
}, function(error) {
return Promise.reject(error);
});
You can handle with standard if statement inside the .then()
return axios.get(`${process.env.BASE_URL}/users`)
.then(response => {
if(response.data.statusCode===442){
...//custom error handling goes here
}else{
...//if statusCode is a success one
}
}).catch(err => {
console.log(err.message);
});
Check the response.data.statusCode value, if it is 442 then you should ideally throw an Error and let it be handled in the .catch callback.
return axios.get(`${process.env.BASE_URL}/users`)
.then(response => {
if(response.data.statusCode===442){
throw new Error(response.data.message); //using throw instead of Promise.reject() to break the control flow.
}else{
//return the data wrapped in promise
}
})
.catch((err) => {
console.log(err.message);
return Promise.reject(err.message);
});

Unexpected callTimes in async functions

I am testing with a react application with sinon, here is some backgrounds
A file uploader is created for user to upload the file to server, after the upload has completed, a dialog box will pop out showing the details of the uploaded files
Container <UpgradeApp />
class UpgradeApp extends Component {
...
onFileUpload() {
this.updateProgressBar(true); // I can only get this spy call detected
return fetch(
`/api/v1/upload-files/`,
{
credentials: 'include',
method: 'POST',
body: formObj,
headers: {'X-CSRFToken': this.props.csrf},
}
)
.then((res) => {
if (res.status >= 400) {
// error handling here...
throw new Error(`Bad server responses, status code: ${res.status}`);
}
return res.json();
})
.then((ans) => {
if (ans.success) {
this.setState({
...this.state,
dialog: {
...this.state.dialog,
submitFn: () => {
return restfulApiCall(
this.props.csrf,
'upgrade',
).then((res) => {
if (res.status >= 400) {
// error handling here...
throw new Error(`Bad server responses, status code: ${res.status}`);
}
}).catch((err) => {
console.log('in catch');
this.updateProgressBar(false); // Want to test whether this fn is called
});
}
}
}
}
});
}
...
}
Test upgrade.spec.js
The test is to check whether the function this.updateProgressBar is being executed, but I only get the called spyed in first call, but not the second one.
From the order of console log message, I can see in catch is before in then, so it is pretty sure that the catch block is being executed before the test case evaluating the function, is there any clues regarding on this? Thank you
...
const spyUpdateProgressBar = spy(upgradeAppInstance, 'updateProgressBar');
it('should hide the progress bar when upgrade is failed', function (done) {
fetchMock.post(regUploadExp, mockOkUploadHttpResponse);
fetchMock.post(regUpgradeExp, mockHttpUpgradeResponse);
upgradeAppInstance.onFileUpload().then(() => {
wrapper.update();
expect(wrapper.find(ADialog).at(0).props().open).to.equal(true);
const mockButtons2 = wrapper.find(ADialog).dive().at(0).find(Button);
expect(spyUpdateProgressBar.calledOnce).to.equal(true); // This test is passed as expected
spyUpdateProgressBar.resetHistory();
// simulate upgrade process
mockButtons2.at(1).simulate('click');
console.log('in then');
});
setImmediate(() => {
console.log(spyUpdateProgressBar.callCount);
expect(spyUpdateProgressBar.calledOnce).to.equal(true); // failed in this expect, expecting true but get false
done();
});
});

fetch promises - return 500 internals server error

I am trying to handle 500 internal server errors inside fetch. If an internal error occurs, the server responds with a message. I want to extract that message.
const req = new Request(url, {
method: node.method,
mode: 'cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
fetch(req)
.then((response) => {
if (response.status === 500) {
// res.json extracts the body from the response as a promise, chain
// .then on it and throw an error to be caught in the lower catch.
response.json()
.then((json) => {
const { message, stackTrace } = json;
throw new ServerException(message, stackTrace); // note 1
})
.catch((error) => {
return Promise.reject(RawException(error)); // note 2
});
} else {
return response.json();
}
})
.then((json) => { // note 3
dispatch(stopLoading());
dispatch(recieveResponse(typeOfRequest, json));
})
.catch((e) => {
dispatch(stopLoading());
dispatch(responseError());
dispatch(showError(e.message));
});
};
My issue is that extracting the body of the response creates a new promise, and I am unable to reject the outer promise from the inner one.
Note 1 triggers the catch method of the inner promise. Inside catch, I have tried throwing another error but it doesn't seem to work. If I throw new RawException(error) on the second noted line, nothing happens and the then method on the third noted line triggers. If I return a rejected promise as I have in the code provided, then still triggers but json is undefined.
How do I do this?
The solution is not to nest promises, but to resolve/return the .then of the outer promise with the conclusion of the inner promise.
if (response.status === 500) {
response.json() // response.json returns a promise, we chose to do nothing with its
.then((json) => { // conclusion
const { message, stackTrace } = json;
throw new ServerException(message, stackTrace); // note 1
})
.catch((error) => {
return Promise.reject(RawException(error)); // note 2
});
} else {
return response.json();
}
Should become
if (response.status === 500) {
return response.json() // return the result of the inner promise, which is an error
.then((json) => {
const { message, stackTrace } = json;
throw new ServerException(message, stackTrace);
});
} else {
return response.json();
}
The else clause can be removed as well if that syntax is preferred. ESLint complains about the else being wasteful, but I perfer the way it makes the code's branching explicit.

Categories