Trying to access error response 500 axios - javascript

I am not able to access the response of error - 500 in axios
export const dowloadFilePDF = (data) => {
return axios
.request({
method: 'GET',
url: `${basePath + data[0]}`,
responseType: 'blob',
headers: { Authorization: Authorization },
})
.then(response => {
console.log(response)
let fileName = response.headers['content-disposition']?.split(';')[1]?.split('=')[1]?.split('"').join('')
fileName = fileName ? fileName : 'data.pdf'
fileDownload(response.data, fileName)
})
.catch((error) => {
console.log(error.response.data)
})
}
I am not getting the response instead its returning as
data : Blob {size: 215, type: 'application/json'}

According to the documentation, you can't assume error.response will be filled in. Here's the code the documentation shows with the inline comments explaining it:
Handling Errors
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
There's another aspect to this as well: You're calling catch on the promise returned by then, not on the promise returned by axios. If the axios promise is rejected, you'll reach that rejection handler, but you'll also reach it if the axios promise is fulfilled but then your fulfillment handler throws an error (or returns a promise it ultimately rejects). In that latter case, the error probably won't have a response property at all.

the best way to catch errors instead of trying a lot of lines of code in the catch method by promise is using the tools in the Axios names interceptor.
interceptor has two property request and response. In response we can simulate the errors status and based on the status code we can do whatever we want. for example :
axios.interceptors.response.use(null, error => {
console.log("error : " , error);
const expectedError = error.response && error.response.status >= 400 &&
error.response.status < 500;
if (expectedError) {
return Promise.reject(error);
}
alert("unexpected error is happen");
});
if you need more help here is the original link

Related

Axios call to Springboot backend responding is not forwarding to new page after returning response

My postmapping "login" in my controller is returning a 200. But I'm getting undefined and I believe it is from my axios call. I know that the undefined error is being reported from the catch block in the console
Axios call -
submit() {
let formData = new FormData();
formData.set("email", this.email)
formData.set("password", this.password)
formData.set("staySignedIn", this.staySignedIn)
// When the client/server sides are running from the same port (AWS) the url for this api call should be changed to /api/v1/login
axios.post("http://localhost:8080/api/v1/login", formData,
{headers: {'Content-Type': 'application/json'}})
.then(function (res) {
console.log(res); // test
if (res.data.code === 200) {
this.router.push('/dashboard')
console.log("success");
} else {
console.log(res.data.code);
}
})
.catch(function (err) {
console.log(err);
})
}
Response from dev tools
Response from test
Axios response schema documentation is here
Unless you have a key code in your controller response, response.data.code will be undefined.
Try res.status instead if you want to check the HTTP status.
axios.post("http://localhost:8080/api/v1/login", formData,
{headers: {'Content-Type': 'application/json'}})
.then(function (res) {
if (res.status === 200) {
this.router.push('/dashboard')
console.log("success");
} else {
console.log(res.status);
}
})
.catch(function (err) {
console.log(err);
})
EDIT
You seem to be sending back the password back in the response. Even though the password is encrypted, better restrict exposing it in the response.

I'm getting "Uncaught (in promise) TypeError: Cannot read property 'data' of undefined" error in axios patch api

I am trying to update an array of objects using an Axios/Node.js API. I have successfully created the array, but when I try to pass in through an axios patch request, I am getting the "Cannot read property 'data' of undefined". Anyone know what I might be doing wrong?
My axios function is below:
export const updateTrans = async (transArr) => {
try {
const res = await axios({
method: 'PATCH',
url: `http://127.0.0.1:7000/api/v1/property/${id}`,
data: {
"transactions": transArr }
});
if (res.data.status === 'success') {
showAlert('success', 'Data updated successfully!');
}
} catch (err) {
console.log(err.response.data.message );
showAlert('error', err.response.data.message);
}
};
I have tried to stringify "transArr" as well, but still no luck.
The problem is that you're accessing err.response.data without checking if err.response exists. err.response is only present if the request was made and there was a response. If, for example, a CORS error or some network error occurred (or some other error inside the try block), it will not be present.
Just check that err.response exists before using it.
try {
// ...
} catch (err) {
console.log(err, err.response && err.response.data);
if (err.response && err.response.data) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
showAlert("error", err.response.data.message);
return;
}
showAlert("error", err.message);
}

Axios post entering catch block even after successful Rest API call completion

My axios post request is not returning the value returned by the API in a non success 401 scenario. It works fine when its a success scenario.
My reset Password API returns the status code, and a message for every call. when I use post man to test its output for resetting a password, giving incorrect current password, I get
Postman Output:
statusCode: 401,
headers: {
.......
........
},
body: "{"code":"NotAuthorizedException","name":"NotAuthorizedException","message":"Incorrect username or password."}" <--- This is the body output
But in my axios post, it goes to the catch block:
await Axios.post(resetAPIUrl, resetParams, config).then(value=> {
console.log(`Returned data ----> ${JSON.stringify(value)}`);
resolve(value);
}).catch(error=>{
console.log(`Failing--->${error}`)
reject(error)
});
this is the error that I am getting in the catch block of Axios post:
Error: Request failed with status code 401
The error reason is correct. But why isn it going into catch block? Its a successful completion of the process. Calling the API directly from post man gives me the correct output structure.
Interceptor was the answer. Since Axios doesn't consider any response other than 200 as the success scenario, interceptors can be used to capture the other responses:
{
Axios.interceptors.request.use(req=>{
console.log(`This is the request ---> ${req.method} ${req.url}`)
return req;
})
Axios.interceptors.response.use(res => {
console.log(`res status ---> ${res.status}`)
resolve(res)
return res;
}, (error)=>{
console.log(`This is the error status ---> ${error.response.status}`)
if(error.response.status === 401){
resolve(error.response);
}
})
await Axios.post(resetAPIUrl, resetParams, config);

Angular 5 HttpClient Error response not catchable

We're working with Angular 5 and a Spring 2 OAuth Backend.
Now when I send an old token it's of course expired. It returns status code: 401 and an error response with invalid token and so on. Now I can't see it in my logs or when I catch the error. I want to get the error so I can at first log it and later on either refresh the token or send him to the Login Page.
Now if i subscribe to the request with:
.subscribe(res => {
//just random stuff.
}, err => {
console.log("error", err);
});
I just see this response in the log with an unknown error like in this image
Could it be failure of the backend? Because i also see in the logs something like a "No 'Access-Control-Allow-Origin' header is present"-error, although it's because of the invalid token.
Although I can see this response code in Google Chrome Dev Tools
and a 401 status code.
So I tried to find a solution myself. I've already got an interceptor and tried it with some solutions
return next.handle(authReq)
.catch(error => {
console.log("im in here");
console.log(error);
return Observable.throw(error);
});
The Http Service just throws an error that catch is not a function without even logging the error or the "im in here".
I have also tried with the .do after next.handle and I got the same error like catch
.do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (err: any) => {
console.log(err);
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
}
}
});
I've tried with pipe after the http.get but it doesn't work either.
http.get(...).pipe(
retry(3), // retry a failed request up to 3 times
catchError(this.handleError) // then handle the error
);
import 'rxjs/add/operator/catch';
Somefunc(){
this.httpClient
.get("data-url")
.subscribe(
data => console.log('success', data),
error => console.log('oops', error)
);
}
OR
this.httpClient
.get("data-url")
.catch((err: HttpErrorResponse) => {
// simple logging, but you can do a lot more, see below
console.error('An error occurred:', err.error);
});
Should work.

How to catch and handle error response 422 with Redux/Axios?

I have an action making a POST request to the server in order to update a user's password, but I'm unable to handle the error in the chained catch block.
return axios({
method: 'post',
data: {
password: currentPassword,
new_password: newPassword
},
url: `path/to/endpoint`
})
.then(response => {
dispatch(PasswordUpdateSuccess(response))
})
.catch(error => {
console.log('ERROR', error)
switch (error.type) {
case 'password_invalid':
dispatch(PasswordUpdateFailure('Incorrect current password'))
break
case 'invalid_attributes':
dispatch(PasswordUpdateFailure('Fields must not be blank'))
break
}
})
When I log the error this is what I see:
When I check the network tab I can see the response body, but for some reason I can't access the values!
Have I unknowingly made a mistake somewhere? Because I'm handling other errors from different request fine, but can't seem to work this one out.
Example
getUserList() {
return axios.get('/users')
.then(response => response.data)
.catch(error => {
if (error.response) {
console.log(error.response);
}
});
}
Check the error object for response, it will include the object you're looking for so you can do error.response.status
https://github.com/mzabriskie/axios#handling-errors
Axios is probably parsing the response. I access the error like this in my code:
axios({
method: 'post',
responseType: 'json',
url: `${SERVER_URL}/token`,
data: {
idToken,
userEmail
}
})
.then(response => {
dispatch(something(response));
})
.catch(error => {
dispatch({ type: AUTH_FAILED });
dispatch({ type: ERROR, payload: error.data.error.message });
});
From the docs:
The response for a request contains the following information.
{
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the headers that the server responded with
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {}
}
So the catch(error => ) is actually just catch(response => )
EDIT:
I still dont understand why logging the error returns that stack message. I tried logging it like this. And then you can actually see that it is an object.
console.log('errorType', typeof error);
console.log('error', Object.assign({}, error));
EDIT2:
After some more looking around this is what you are trying to print. Which is a Javascipt error object. Axios then enhances this error with the config, code and reponse like this.
console.log('error', error);
console.log('errorType', typeof error);
console.log('error', Object.assign({}, error));
console.log('getOwnPropertyNames', Object.getOwnPropertyNames(error));
console.log('stackProperty', Object.getOwnPropertyDescriptor(error, 'stack'));
console.log('messageProperty', Object.getOwnPropertyDescriptor(error, 'message'));
console.log('stackEnumerable', error.propertyIsEnumerable('stack'));
console.log('messageEnumerable', error.propertyIsEnumerable('message'));
Here is the proper way to handle the error object:
axios.put(this.apiBaseEndpoint + '/' + id, input)
.then((response) => {
// Success
})
.catch((error) => {
// Error
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
// console.log(error.response.data);
// console.log(error.response.status);
// console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
Origin url https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253
axios.post('http://localhost:8000/api/auth/register', {
username : 'test'
}).then(result => {
console.log(result.data)
}).catch(err => {
console.log(err.response.data)
})
add in catch
geting error response ==> err.response.data
I was also stumped on this for a while. I won't rehash things too much, but I thought it would be helpful to others to add my 2 cents.
The error in the code above is of type Error. What happens is the toString method is called on the error object because you are trying to print something to the console. This is implicit, a result of writing to the console. If you look at the code of toString on the error object.
Error.prototype.toString = function() {
'use strict';
var obj = Object(this);
if (obj !== this) {
throw new TypeError();
}
var name = this.name;
name = (name === undefined) ? 'Error' : String(name);
var msg = this.message;
msg = (msg === undefined) ? '' : String(msg);
if (name === '') {
return msg;
}
if (msg === '') {
return name;
}
return name + ': ' + msg;
};
So you can see above it uses the internals to build up the string to output to the console.
There are great docs on this on mozilla.
The only thing what helped me was the following:
axios.put('/api/settings', settings, {
validateStatus: status => status >= 200 && status < 300 || status === 422
})
https://stackoverflow.com/a/66285529/5849569
You can use inline if else statement like so:
.catch(error => {
dispatch({
type: authActions.AUTH_PROCESS_ERROR,
error: error.response ? error.response.data.code.toString() : 'Something went wrong, please try again.'
});
});
I recommend handling errors via Axios interceptors, individually for each case scenario:
// interceptor to catch errors
const errorInterceptor = (error) => {
// check if it's a server error
if (!error.response) {
console.log('📡 API | Network/Server error')
return Promise.reject(error)
}
// all the error responses
switch (error.response.status) {
case 400:
console.error(error.response.status, error.message)
console.log('📡 API | Nothing to display', 'Data Not Found')
break
case 401: // authentication error, logout the user
console.log('📡 API | Please login again', 'Session Expired')
localStorage.removeItem('user')
break
case 403:
console.error(error.response.status, error.message)
console.log('📡 API | Access denied', 'Data Not Found')
break
case 404:
console.error(error.response.status, error.message)
console.log('📡 API | Dataset not found', 'Data Not Found')
break
case 422:
console.error(error.response.status, error.message, error.response.data.detail)
console.log('📡 API | Validation error', 'Unprocessable Content')
break
default:
console.error(error.response.status, error.message)
}
return Promise.reject(error)
}

Categories

Resources