I am using standard http service to send requests to server.
Sometimes server returns data with 503 HTTP error.
http.post<...>(url, body).pipe(map(result => {
console.log(result);
return result;
}),
catchError(err => throwError(err)));
I fall into catchError every time server returns HTTP error code. What I want to do - is to access the whole HTTP response (that contains some useful data even if HTTP error is returned within response).
How can I do that?
Thank you in advance!
You can subscribe the request and catch the error like this:
this.http.post(url, body).subscribe(
data => {
console.log(data);
},
err => {
console.log(err); // err.error for example for specific attribute
});
I hope this is helpfull.
Related
I am using the fetch-API to send a GET request to a Spring Boot backend. The request looks somewhat like this:
const response = await fetch(url);
if (response.status === 200) {
// do something
} else {
response.json().then(response => console.log(response));
}
In case that I send a valid request, i.e. the url passed into fetch() is valid, everything works fine. In case that I pass an invalid url into fetch(), however, two things appear to be happenning:
A serer response message is thrown:
My Spring Boot backend return a ResponseEntity with a custom error message as body. This error message is logged inside the else-block of the above code snippet:
While I do expect the second point to be happenning, I cannot explain the first. I don't understand why this server-response error is logged into my browser console. I do have a few catch-blocks inside my code, something like:
const response = await fetch(url).catch(error => console.log(error));
As far as I know, however, fetch only throws an error if a network connection error occurred or similar. A response code not equal to 200 does not result in fetch throwing an error. So, as I said, I don't know where this error message comes from and I was hoping that somebody does, maybe it is something generic to the fetch API that I just don't know?
I recommend using "try catch" to better capture errors.
If the response is positive and it's a json, use a "then" after the fetch.
try {
const response = await fetch(url).then(res => res.json());
// do something
} catch (e) {
console.error(e);
}
If you're getting a 400 error, check the api documentation to see if you're passing the parameter incorrectly. or if that is not the route
I am working on a project with API. API response is 404 not found. I need to handle this status code without a new page. I want to add an window.confirm("not found"). However, I couldnt do that, because when API says 404 there is no response so I couldn't check the response. How can I do that without using new page? How can I handle that? Here is my response code:
const response = await instance.get(`?q=${q}&appid=${appid}`);
if (!response) {
console.log("ceren");
}
It never prints "ceren". I tried response ==="", response ===null, response.data===null, and so on
The response object is never null. It's an object that, along with many other keys, includes the status. Moreover, if the request fails, it will throw an error (due to the await, though outside of this function it will be a Promise rejection), so you can just catch that:
return instance.get(`?q=${q}&appid=${appid}`).then(/*...*/).catch((error) => console.log('Request failed!'));
Or, if you must use an await:
try {
const response = await instance.get(`?q=${q}&appid=${appid}`);
} catch (error) {
console.log('Request failed!');
}
I have made a GET request to an API which rejects GET requests with a 400 error (and "Invalid request") response; and while I can catch and handle the response data, there is another error line which I can't catch:
GET https://API address/test 400
My code is as follows:
try {
let res = await this.axios.get(API)
console.log(res.data)
} catch (error) {
console.log(error.response.data)
}
I did also try this as a promise chain (with a catch) - but same result and I was thinking that wrapping everything in a try catch would do the trick.
My API code (hosted on Firebase) is as follows:
exports.test = functions.https.onRequest((request, response) => {
cors(request, response, () => {
if (request.method !== 'POST') {
return response.status(400).send('Invalid request.')
}
response.status(200).send("Hello from Firebase!");
})
});
First line is when I send a POST request, and the rest comes back after the GET request:
How do I handle that GET error? And where is it coming from?
If I correctly understand your question, it seems you are calling the Cloud Function with a wrong URL.
You use
https://us-central1-xxxxxx.cloudfunctions.net/helloWorld
as shown in the first version of your question,
when you should use
https://us-central1-xxxxxx.cloudfunctions.net/test
since your Cloud Function is defined with
exports.test = functions.https.onRequest()
You'll find the corresponding doc here: https://firebase.google.com/docs/functions/http-events#invoke_an_http_function
Update following your comment:
It is normal that GET shows an error since you have the following code:
if (request.method !== 'POST') {
return response.status(400).send('Invalid request.')
}
Since GET is not a POST you enter this if and get a 400 error...
I am using Puppeteer api (https://github.com/GoogleChrome/puppeteer)
For automation testing.
I want to listen to all http response, need the url and the response data for each one.
I try to so use the page.on('response') function :
page.on('response', response => {
response.text().then( textBody=> {
const req = response.request();;
console.log(req.url())
console.log(textBody)
});
})
Should warp in 'waitForSelector' function , to have a flag that the data is ready?
I try to do so.
The problem is some time i do not see any console.log and some time i do.
I will glad to know what do i do wrong?
There is no need to call response.request(), unless you are trying to obtain the URL of the matching request object.
The following solution will work just fine:
page.on('response', response => {
console.log('Response URL:', response.url());
response.text().then(data => {
console.log('Response Text:');
console.log(data);
});
});
If you are still having issues, it could be because the associated request has failed.
You can check for this error by listening for the requestfailed event and logging the result:
page.on('requestfailed', request => {
console.log('Failed Request URL:', request.url());
console.log('Failed Request Error Message:', request.failure().errorText);
});
As said in the title, nothing is happening when I subscribe to my observable. There is no error in the console or during the build. Here is my code :
My service
getBlueCollars(): Observable<BlueCollar[]> {
return this.http.get(this.defaultAPIURL + 'bluecollar?limit=25').map(
(res: Response) => {
return res.json();
});
}
My component
ngOnInit() {
this.planifRequestService.getBlueCollars().subscribe(
data => {
this.blueCollars = data;
console.log('Inner Blue Collars', this.blueCollars);
},
err => console.log(err)
);
console.log('Value BlueCollars : ', this.blueCollars);
}
So the second console.log is triggering with "Value BlueCollars : Undefined", and the log in my subscribe is never showed. As well, I can't see the request sent in the Networt tab of Chrome.
So I tried to simplify everything with the following code :
let response: any;
this.http.get('myUrl').subscribe(data => response = data);
console.log('TestRep: ', response);
Same problem here, no error, response is undefined. It seems the subscribe is not triggering the observable. (The URL is correct, it is working on my swagger or with postman.)
I'm on Angular 2.4.9
Edit
So I tried to copy/past the code of my request on a brand new project, everything is working fine. The request is triggered and I can get the JSON response correctly. So there is something maybe on the configuration of my project that is forbiding the request to trigger correctly.
Ok just found what was going on. I am using a fake backend in order to try my login connexions that is supposed to catch only specified URL. However for wathever raison it was catching all the requests, so that explain everything. Thx for your help everybody.
Try adding a catch block to your service code:
getBlueCollars(): Observable<BlueCollar[]> {
return this.http.get(this.defaultAPIURL + 'bluecollar?limit=25')
.map(
(res: Response) => {
return res.json();
})
.catch(err => Observable.throw(err))
}
Don't forget to
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';`
I imagine this will result in the error that'll give you an idea where your code is going wrong.
The reason the console.log outside the subscribe call is undefined is because the subscribe/http call is happening asynchronously and so, in effect, the order (in time!) the code is running is:
1) the observable is subscribed to (and then waits for a response)
2) the outer console log runs with blueCollars undefined
3) when the response (or error) comes back from the http request (potentially after several seconds), only then will the inner assignment of this.blueCollar = data happen (and the inner console log), OR an error will get logged
Apart from that the subscribe code looks fine...!