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.
Related
I am trying to run an old react app, it compiles successfully on Terminal but on the browser it does not run and gives me this message "Request failed with status code 423"
I am a beginner, I have searched and found this:
The 423 Locked status code means the source or destination resource of a method is locked. This response SHOULD contain an appropriate precondition or postcondition code, such as ‘lock-token-submitted’ or ‘no-conflicting-lock’.
But I don't know what should I do. Any idea or solution?
first, you have to find the API call that makes the error, then handle/catch the error to prevent app crashing, e.g:
catch method:
axios(...).catch(console.error);
async/await:
async function apiCall() => {
try {
const {
data
} = axios(...);
} catch (error) {
console.error(error)
}
}
and about the HTTP request error, you should ask about that from the API maintainer/developer.
Problem:
I am seeing following error in my browser console, I don't want a solution to resolve this error.
I want a solution to remove from the browser console.
GET https://logo.clearbit.com/objectivepartners.com net::ERR_ABORTED 404
I came to following solution which can handle consoling but while using fetch
it is not working:
console.defaultError = console.error.bind(console);
console.errors = [];
console.error = function(){
if (!arguments[0].includes("404")) {
console.defaultError.apply(console, arguments);
}
console.errors.push(Array.from(arguments));
}
fetch("https://logo.clearbit.com/objectivepartners.com").then(response => {
if (response.ok) {
console.log("okay");
}
}).catch(error => {
console.error("404"); // WILL NOT SHOW IN BROUSER CONSOLE
console.error("error"); // WILL SHOW IN BROWSER CONSOLE
});
Here,
I want if arguments include 404 then do not console it in the browser.
But on the fetch request failure, it includes 404 still it consoling, that I do not want to be happening
could it be possible that when fetch fail i can disable using in this code (by changing) or any other way?
Unfortunately, I didn't find any solution to resolve at the client-side or using javascript.
But I resolve this by creating an endpoint to API side and giving URL to that API to check that URL is valid or not, based on API response I handled in fetch
I wrote a function that keeps returning an Access-Control-Allow-Origin error. This is actually fine for me; I don't want to fix this. I just want to catch it so I can read its message in my program.
All the code that causes the error to be thrown is within my try block, and my catch block displays the error's string message. However, when I run the code, no error is caught, and the error shows up in red in the console. How do I catch this error and store its message?
try {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (this.status < 400 && this.status >= 300) {
console.log('this redirects to ' + this.getResponseHeader("Location"));
} else {
console.log('doesn\'t redirect');
}
}
xhr.open('HEAD', $scope.suggLink, true);
xhr.send();
} catch(e) {
console.log('Caught it!');
console.log(e.message);
}
While browsers will log a more-detailed error message to the console, you can’t access that from your code. See https://bugs.chromium.org/p/chromium/issues/detail?id=118096#c5:
The details of errors of XHRs and Fetch API are not exposed to JavaScript for security reasons.
As far as the what specs actually require here, the Fetch spec is what defines the details of the “status message” to provide in case of an error — even if XHR is used instead of the Fetch API (the XHR spec references the Fetch spec). And for any network error or response blocked by the browser, the Fetch spec requires that the status message be “the empty byte sequence”:
A network error is a response whose status is always 0, status message is always the empty byte sequence, header list is always empty, body is always null, and trailer is always empty.
So all you can get back from any error you can catch is “TypeError: Failed to fetch” or such.
If you’re using XHR, all you have for handling an error is the onerror event handler:
xhr.onerror = function() { console.log("Error occurred but I dunno what exactly.")}
jquery version of above (sideshowbarker's) workaround for CORS error:
let sURL = 'https://www.mocky.io/v2/5185415ba171ea3a00704eed';
$.getJSON(sURL, function (json)
{
console.log('json from web-service ->', json);
})
.fail(function()
{
console.log("error - could not get json data from service");
});
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);
});
I am using isomorphic-fetch to perform AJAX requests from my react-redux application. In my api middleware I have the following function which calls the external resource:
import fetch from 'isomorphic-fetch';
function callApi({ endpoint, method, body, params = {} }) {
let route = generateRoute(endpoint, params);
return fetch(route, generateFetchOptions(method, body))
.then(response => {
if (!response.ok) {
return Promise.reject(response);
}
return response.json();
});
}
The above function is called by the following piece of code:
return callApi(callAPI).then(
response => next(actionWith({
response,
type: successType,
statusCode: 200
})),
error => error.json().then(errorObject => {
return next(actionWith({
type: failureType,
statusCode: errorObject.statusCode,
error: errorObject.message || 'Something bad happened'
}));
})
);
If I reject with Promise.reject(response) the error is being handled by the error handler, but for some reason the error also bubbles to the browser console (in my case Chrome).
Here is a screenshot from the console which shows what is happening (api.js:34 is the second line of the callApi method):
This is the usual behavior (in probably every browser?) when hitting an error during an HTTP request (no matter whether a linked image cannot be found, or an XHR fails). No matter if and how you handle those errors, they will always be logged to the console. There is no way to suppress this behavior.
References:
Provide a way not to display 404 XHR errors in console
How can I stop jQuery.ajax() from logging failures to the console?