Angular catching "standard" errors instead of my API's errors - javascript

I have a service that looks like this:
return this.http
.post(requestUrl, body, { headers, observe: 'response' })
.toPromise()
.then((res: any) => {
return res.body?.data || res?.body?.message;
}).catch((err) => {
console.log('error', err);
})
When i trigger an error, this is what i get on the console.log:
error Error Code: 400
Message: Http failure response for <MY API ENDPOINT>: 400 OK
But on the network tab (Google chrome dev tools) i see this:
{
"message": "Unsupported value, please contact support.",
"status": "failure"
}
How can i read my message that i'm sending from my Backend in my angular .catch block?

Related

Trying to access error response 500 axios

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

Vue axios error Uncaught (in promise) Error: Request failed with status code 415

I hope you all are well!
I have a error in vue axios
Uncaught (in promise) Error: Request failed with status code 415
Here's my code
authService.Login(user)
.then(resp => {
if (resp.data.success) {
resolve(resp)
}
})
.catch(err => {
reject(err)
})
Login (data) {
return shaxios.post('api/Auth/Authorize', data)
}
You may send a JSON object to an API expecting a Form URL-encoded HTTP POST request.
Have you checked https://axios-http.com/docs/urlencoded ?

How do I show message on 403 client side if the email fails to send?

I am trying to show alert message when the email sends or gets failed. If it fails, I'm getting 403 from the backend. But not sure how do I show it here in client-side. If success, I get a 200. Right now, in the case of failure, if I console.log(res)(as you can see below), it shows
res is not defined
Uncaught (in promise) Error: Request failed with status code 403
And in network tab, I get the response. That's alright.
I just want to show it here client side in my react component.
handleClick = (id) => {
axios
.post(`http://localhost:3000/api/v1/users/send-post/${id}`)
.then((res) =>
console.log(res),
res.status === 200 ? alert("Email sent"): null
)
.catch((err) => {
if (err) {
return alert("Sorry, Something went wrong")
}
})
}
The error status is in err.response.status.
Modify
if (err) {
return alert("Sorry, Something went wrong")
}
with
if (err) {
return alert("Sorry, Something went wrong. Status "+ err.response.status)
}
For reference, you check this link https://stackoverflow.com/a/39153411/12680971
You have a comma , after console.log call.
Do next:
.then(res => {
console.log(res);
res.status === 200 && alert("Email sent");
})
Or another variant:
.then(res =>
console.log(res) ||
res.status === 200 ? alert("Email sent") : null
)

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.

Get a JSON response from an API?

I'm posting to an api where a failed response is output on purpose:
return response()->json([
'message' => 'Record not found',
], 422);
In Chrome dev tools I can see I get a 422 response with the response of {"message":"Record not found"}
In javascript I wish to get the message and log it, but i'm struggling to do so, here's my javascript:
axios.post('/api/test', {
name: 'test'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error) //this is Error: Request failed with status code 422
console.log(error.message); //this is blank
});
How can I get the message?
I found a code that can help you understand the catch block very well here :
axios.post('/api/test', {
name: 'test'
})
.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);
});
try to catch like this:
.catch(function(error){
console.log(error);
if (error.response) {
console.log(error.response.data.message);
}
});

Categories

Resources