fetch('https://api.postcodes.io/postcodes/aassdd')
.then((resp) => {
console.log(resp.status);
})
.catch((e) => { console.log('ha'); });
For some odd reason the code above will still throw error and execute the .then statement afterwards. Is there a way to fix this ?
Edit: fiddle
Most browser developer consoles normally logs 404 errors by default, and some may, or can be configured to, log all requests.
The fact that you see see an error here doesn't mean a catch-able JavaScript exception was thrown, in addition to JavaScript console logs and throw exceptions, the browser console also shows other things.
There isn't anything you can do in your code to stop this error from appearing in the console, but some consoles would let you hide those requests from the console.
Also, fetch does not throw an error on typical error response codes like 404. This is to make it more-flexible, and let you decide if you still want the content, even if it is a 404 response code.
If you want to throw an error on a non-200 status code, you could do this:
fetch('https://api.postcodes.io/postcodes/aassdd')
.then((resp) => {
if (resp.status !== 200) {
throw new Error('Invalid status code: ' + resp.status);
}
})
.catch((e) => { console.log('ha'); });
Related
Is there a way with the HttpClient to remove error messages from the browser console?
My current code looks like this:
getStuff(stuffId: string): Observable<Stuff[]> {
return this.httpClient.get<Stuff[]>(this.stuff() + stuffId + '/stuff/').pipe(
catchError((err) => {
console.log(err.status);
if (err.status === 404) {
console.log('Not found');
}
})
);
}
My console.log('Not found') within the if statement is executed, but it still throws the standard error to the console.
My goal: nothing red in the console :)
UPDATE:
The errors are not thrown in Firefox, but in Google Chrome. Why..?
The standard error you are seeing in console is actually not from code. Its from network, due to API error. The browsers consider and understand standard http response codes. So, whenever any response code other than 2xx is returned by any http request, they consider it an error and show it in red in console.
Unfortunately you cannot remove it. That's done by browser.
Callback to catchError has to return an Observable so you can just return for example EMPTY that just completes and emits nothing:
import { EMPTY } from 'rxjs';
...
catchError((err) => {
console.log(err.status);
if (err.status === 404) {
console.log('Not found');
}
return EMPTY;
});
I am having some problems with catching nodejs fetch exceptions
What I am expecting to happen is:
HTTP error of some sort occurs in my fetch call
CheckResponseStatus function runs and an error an error is thrown with the server error status and text
This error is caught and the ServerError function runs which (just for testing) will just print the error to the console.
However, the error printed to the console is:
Cannot connect to Server. Check you are using the correct IP Address and the server is running.
FetchError: request to http://localhost:3689/api/outputs failed, reason: connect ECONNREFUSED 127.0.0.1:3689
This is implying that the error I have thrown is not being caught, some default fetch error is being caught, and CheckResponseStatus is not being run.
My code is below
Node-Fetch HTTP Request:
async function getStatus(serverip,serverport){
return await fetch(`http://${serverip}:${serverport}/api/outputs`)
.then(this.checkResponseStatus)
.then(res => res.json())
.catch((err) => this.ServerError(err));
}
CheckResponseStatus Function:
checkResponseStatus(res) {
if(res.ok){
return res
}
//will add elseif's here for different HTTP errors
else {
throw new Error(`The HTTP status of the response: ${res.status} (${res.statusText})`);
}
}
ServerError Function:
ServerError(err){
console.log('Cannot connect to Server. Check you are using the correct IP Address and the server is running.');
console.log(err);
}
Thanks for any suggestions or help.
If fetch is unable to connect to the remote server, it will reject. In your code, checkResponseStatus is never called because fetch is never able to get a response; the first two .then blocks are skipped because fetch rejected, so execution goes directly to the .catch block.
If you want network errors to run through checkResponseStatus, you can add a second .catch before the first .then and format the error into a "response":
fetch(`http://${serverip}:${serverport}/api/outputs`)
.catch(err => {
// return a mock failed response for checkResponseStatus to handle
return {
ok: false,
status: -1,
statusText: 'Network Failure',
};
})
.then(this.checkResponseStatus)
.then(res => res.json())
.catch((err) => this.ServerError(err));
However, I believe your code is currently running how I would expect it to - a network failure skips checkResponseStatus, which makes sense because there's no real response to check.
Can we explicitly and specifically catch Puppeteer (Chromme/Chromium) error net::ERR_ABORTED? Or is string matching the only option currently?
page.goto(oneClickAuthPage).catch(e => {
if (e.message.includes('net::ERR_ABORTED')) {}
})
/* "net::ERROR_ABORTED" occurs for sub-resources on a page if we navigate
* away too quickly. I'm specifically awaiting a 302 response for successful
* login and then immediately navigating to the auth-protected page.
*/
await page.waitForResponse(res => res.url() === href && res.status() === 302)
page.goto(originalRequestPage)
Ideally, this would be similar to a potential event we could catch with page.on('requestaborted')
I'd recommend putting your api calls and so in a trycatch block
If it fails, you catch the error, like you are currently doing. But it just looks a bit nicer
try {
await page.goto(PAGE)
} catch(error) {
console.log(error) or console.error(error)
//do specific functionality based on error codes
if(error.status === 300) {
//I don't know what app you are building this in
//But if it's in React, here you could do
//setState to display error messages and so forth
setError('Action aborted')
//if it's in an express app, you can respond with your own data
res.send({error: 'Action aborted'})
}
}
If there are not specific error codes in the error responses for when Puppeteer is aborted, it means that Puppeteer's API has not been coded to return data like that, unfortunately :')
It's not too uncommon to do error messages checks like you are doing in your question. It's, unfortunately, the only way we can do it, since this is what we're given to work with :'P
I'm using Vue.JS on the front end, Laravel on the backend, and Axios to post some form data, my axios method is set up like below:
axios
.post("/api/xxxxx", formData)
.then(function(response) {
console.log('inside then');
console.log(response.data);
self.errorMessage = response.data.data.message;
})
.catch(function(error) {
console.log('inside catch');
console.log(error);
self.errorMessage = error.response.data.message;
});
},
Everything works as expected within the 'then' block, but when I clear my cookies and cache and resubmitting, the code in the catch block is triggered however this time no error message is displayed on the front end (using errorMessage).
When I check Vue Dev tools, I can see **Error: Unexpected end of JSON input**.
And in my console: Cannot read property 'data' of undefined
So I guess the error here is showing up as undefined.
What I want is for my errorMessage to contain the message from the response whenever there is an error.
When I check my network tab and preview the response, I do see data.message containing the relevant text: ("Something's gone wrong") But I'm not sure why I can't get this to display when the code in the catch block is triggered.
I've managed to load data and to save data. But cannot understand the error handling scheme needed.
When everything goes fine I receive the same object in that was sent but with an extra attribute _saving (false).
When something goes wrong, for instance try to store a string instead of a number, I'll get:
Bad request (error on the console, don't want that)
The response object (might be usefull to show an error)
"Uncaught (in promise)" error
Example:
Code:
this.save()
.then(function(result) {
console.log('ok1', result);
}).catch(function() {
console.log('errorHandler1');
});
OK:
Error:
I've been trying to use catch on promises, following this guidelines:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
but had no luck at all.
This should should work buy just changing p1.then to thisObjectThatIWantToSave.save.then but it didn't.
p1.then(function(value) {
console.log(value); // "Success!"
throw 'oh, no!';
}).catch(function(e) {
console.log(e); // "oh, no!"
}).then(function(){
console.log('after a catch the chain is restored');
}, function () {
console.log('Not fired due to the catch');
});
Again, it still stores the information when the data is correct, the problem I see is that I don't have the tools to decide when was the data correctly stored or not and to avoid triggering errors that can be correctly handled.
I'm using
canjs v3.0.0-pre.11
a restful API provided by feathers
Regarding the error handling ...
Bad request (error on the console, don't want that)
There's no way of preventing the error on the console. This is something chrome does.
The response object (might be usefull to show an error)
You can read the reason for the rejection in can-stache like {{promise.reason}}.
"Uncaught (in promise)" error
I'm not sure why this is being thrown as clearly, your catch is being hit. If you change it to:
this.save()
.then(function(result) {
console.log('ok1', result);
},function() {
console.log('errorHandler1');
});
Do you get the same behavior?