Occasionally, when I run my puppeteer script, I’ll get a “page crashed” error. It’s most likely not a software error, but something to do with the proxy IPs I’m using/webpages I’m scraping. So all I’m really looking to do is just catch the error, close the current page, and open up a new page.
However, my try catch block doesn’t seem to be working. My code is structured like this:
try {
//puppeteer code
}
catch(e) {
console.log(‘caught error ‘ + e);
}
But when the page crashed error happens, I see “unhandled promise rejection error” instead of my console.log message. What’s going on here?
From here:
page.on('error', msg => {
console.error(...);
throw msg ;
});
And this is also advised to globally catch all uncaught errors in your code:
process.on('unhandledRejection', error => {
console.error(...);
throw error;
});
Related
From backend I am getting specific error message during the post request. How may I get this message in javascript?
catch(err => console.log('error', err.response.data))
With this code I am getting just the type of the error, but I need the message which I throw from backend. F.ex throw ConflictException("The name is already exist"). I need get the following message "The name is already exist", not just the the type.
<!DOCTYPE html>
<html>
<body>
<script>
try {
throw new Error('Custom Exception');
}
catch(err) {
if(err.message){
console.log('inside if & error message as follow : ',err.message);
}else {
console.log('inside else');
console.log(err);
}
}
</script>
</body>
</html>
Above is for demonstration purpose, if it still not working then try
catch(err => console.log('error', err?.message));
Caught errors generally have a message field stored at error?.message or if you using things like Axios or other API requests, error messages are generally at error.response?.data?.message!
Note: ?. is an optional chaining to prevent other errors like Can not read properties of undefined, reading x
When fetching postcode from Postcode io API, I tried this error handling code:
async getCoord() {
const postcodeAPI = `http://api.postcodes.io/postcodes/dt12pbbbbbbbbb`;
let response;
try {
response = await fetch(postcodeAPI);
}
catch (e) {
console.log(e);
};
};
The fetch method returns a 404 error as postcode is invalid. In my understanding the try block should be tried and skipped and the error should be caught by the catch method, but instead I got this red 404 error in console:
which happens in the try block, and is the same as no error handling in the code. Why does this happen? Is it because this is browser default behaviour? Is there a way to improve the error handling here?
EDIT
What I wanted was the red console error to disappear and show my own error information instead, but the console error seems unavoidable.
Fetch API doesn't throw errors on any status code. It only throws errors on network failures, i.e. when it couldn't finish the request itself.
You can use response.ok to check if the request finished with 2XX status code.
async getCoord() {
const postcodeAPI = `http://api.postcodes.io/postcodes/dt12pbbbbbbbbb`;
let response;
try {
response = await fetch(postcodeAPI);
if (!response.ok) throw new Error('Request failed.');
}
catch (e) {
console.log(e);
};
};
You can also explicitly check the status code if you need:
if (response.status === 404) {
// handle 404
}
As for your question about logging 404 errors in the console, there's no way or need to avoid it. Whenever you make a request, it's being logged in the dev tools. But dev tools are just what they are called - tools for devs. You can safely assume your users won't look there and even if someone does, having 404 there is not the end of the world.
I want to bullet-proof some code which takes user input and attempts to fetch data from a URL.
I have something like the following:
fetch(url)
.then(response=>{
console.log(response.ok);
response.text();
})
.catch(error=>console.log(error));
There’s more afterwards in the actual code.
If I enter something like http://rubbish I catch a TypeError which I can handle. If I enter something like rubbish (without the http:// protocol), I get an error like :
GET file:///…/rubbish net::ERR_FILE_NOT_FOUND
and then get my TypeError. The actual error occurs on the first line of the code above, before the catch() block.
What is the correct way to handle an error like this?
I’m doing this in an Electron App, so one thing I don’t have to worry about is browser compatibility.
You could potentially execute different logic in the catch block depending on the type of error. For example:
fetch(url)
.then(response=>{
console.log(response.ok);
response.text();
})
.catch(
if (err instanceof TypeError) {
// Handle this normally
} else {
// Execute other logic depending on the type of error you are receiving
}
);
Hope this helps, good luck :)
To make sure that our request will be successful, first, we check the internet connection then send our request.
like this:
NetInfo.isConnected.fetch().then(async isConnected=> {
if(isConnected){
try {
let result = await fetch(MY_REMOTE_SERVER);
console.log("result: ", result)
} catch (error) {
console.error("error: ", error);
}
}
else ToastAndroid.show('No internet', ToastAndroid.SHORT);
});
Everything was fine, until I faced this issue: consider a situation in which access to a server for some countries is blocked.
So, although the internet connection is ok, each time I was getting network request failed error.
I couldn't find the problem because expected the catch to print the error, but my app was just crashing.
Now that I know the reason, I don't know how to solve it.
For example, when the connection can't be made I want to alert the user to use a VPN or leave the app because they are in an embargoed country!
On the other hand, what is the point of catch!? if it doesn't catch the error!
thanks.
Actually this is a mistake on our side, react-native will crash as it encounters console.error.
so by changing the above code to this version you will get rid of the red screen:
NetInfo.isConnected.fetch().then(async isConnected=> {
if(isConnected){
try {
let result = await fetch(MY_REMOTE_SERVER);
console.log("result: ", result)
} catch (error) {
// use "log" instead of "error"
console.log("error: ", error);
// or you may want to show a toast on error like
oastAndroid.show('No internet', ToastAndroid.SHORT)
}
}else ToastAndroid.show('No internet', ToastAndroid.SHORT);
});
How do I listen to an uncaught exception error in meteor?
The errors are of course specific to the cause, so please can you provide a pseudo style code/explanation that states the concept of handling this error.
An example use case:
A user clicks 'logout' but there is an uncaught exception and the user does not get logged out and so the connection to the server remains open.
You can use the callbacks, they usually provide a reason parameter. E.g
Meteor.call("some_random_non_existent_method", function(err, result) {
if(err) return alert(err.reason)
});
Most meteor callbacks have a error param. With the logout its Meteor.logout(function(err) { ... })
You should be able to catch most types of errors like this. If you want to capture all errors you can use try..catch. Everything in the try block will try to run until it throws an error. You can catch this and provide feedback to the user.
try {
//This will throw an error
this.run_something.go_make_error()
}catch(e) {
alert("There was an error running this");
}