Handling error messages in browser console while using fetch - javascript

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

Related

Angular 10 subscribe is failing to post with error code OK(and no other errors shown)

I am new to angular 10 and I am trying to make an http post to a PHP file as shown below
this.http.post(`${environment.server}/path/file.php`, {param1, param2})
.subscribe(
data => {
console.log(JSON.stringify(data));
},
error => {
console.log(error);
this.error = error;
});
The file is successfully called and returns the following JSON as displayed in the console response
{"Email":null,"school_year":2021,"academic_year":"2021"}
When I make the request I am immediately taken to the error state and all the console log is showing below only prints "OK"
console.log(error);
The two questions are the following
Why am getting to the error when the file is successfully returning JSON
Is there a way to get a more helpful error message than just OK
You will need to set the content type to application/json
You would be better off if you used a rest API rather than using php files. .NET Core or Node.JS would give you a better development experience.
It seems that your back-end PHP send the response with status code 400. It should be revised to 200 to get the data in response. When Status code is in Error range like 400, 401, 403 ... http Response will resolved in error or catch part.
In addition if you want just get data, it's better to use GET instead of POST.

How to handle 404 error in a async/await?

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.

Good way to parse error object in catch(e) statement after API call?

When using an api I often find myself with a rather complicated error object.
Depending on the API that I am using the error texts are quite helpful and I would actually sometimes like to display them directly to the user. The problem, of course, is that the error objects can look quite differently so it would be very verbose to go through them and pick individual objects in case they exists (dependant on the status code of the error).
Is this just the nature of the error object or is there a better way to do this?
What I do to handle API calls that end up with error is this:
try {
const response = await axios.post("Your URL");
// Your code to handle the result
} catch (error) {
console.log(error.response.data.error)
// Code to display the error to the user
}
error.response.data.error is the actual error message sent from the server, not the error code

readableStream is locked while using .json()

everyone!
I got a problem: I'm trying to validate registration form. Totally, it works ok, but I need to validate form via server. In my case, for example, I need to figure out if email is already taken.
I tried to fetch and async/await syntax, but problem is still the same:
DOMException: "The operation was aborted. "
The way I understand it right now is readableStream (what actual response body is) is locked. So the wrong error is thrown, and I cannot get server response.
try {
const response = await fetch(options.url, options.requestOptions);
const body = await response.json();
if (options.modifyDataCallback instanceof Function) {
body.data = options.modifyDataCallback(body.data);
}
return body.data;
} catch (error) {
throw error;
}
How do I see the solution? I send request and recieve some server error like
code: email_in_use
message: Email '...' is already in use.
Then I need to throw error and catch it in other place in order to show corresponding error message to client.
In browsers network tab I do receive what I want to receive, but can't get the same JSON-response in my code.
Google chrome provided more information: net::ERR_HTTP2_PROTOCOL_ERROR 200.
And the problem was on backend. It is written in C# and API method returned Task. The problem was solved by adding async/await for this method.

Can't catch errors from ember backgroundReload

Let's says we have a UsersIndexRoute where we load all users.
model() {
return this.store.findAll('users');
}
When we load the page for the first time (hard reload) and get a HTTP 500 errorback we get this error in the ApplicationRoute's errors() and can render a error page and everything is fine.
But:
Let's says we already loaded the Ember App but only loaded a subset of all users, go to the /users page and call the findAll again, Ember immediately gives back the subset of users we already loaded in the store and fetches all the other users in a background request.
Now in our case we get a HTTP 500 error back in the backgroundReload, but it seems like https://github.com/emberjs/data/blob/master/packages/ember-data/lib/system/store.js#L1027 doesn't return the promise array back and we can't catch the error in our findAll method anymore, or receiving any error in the ApplicationRoute's error().
My question is: how and where can I catch errors from backgroundReload?
You can catch any error using .then() method:
model() {
return this.store.findAll('users')
.then(null, (error) => {/*do smth*/});
}
Here is the GH Issue that discusses the topic and also gives a "solution" to the problem: https://github.com/emberjs/data/issues/3809

Categories