JS fetch() | How to hide console error on 404? [duplicate] - javascript

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;
});

Related

Can We Explicitly Catch Puppeteer (Chrome/Chromium) Error net::ERR_ABORTED?

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

How should i catch and handle 406 error in VUEJS

I have a route where i send to the api the day and h to verify in database if there is an opening in a schedule, if is not the api is sending 406. And i'm getting in console 406 error.
How should i handle that error to have a clean console?
You can simply wrap an api call into try-catch and simply don't to do anything with e in catch part.
try { ... you code here ... } catch(e){}
If you are using Axios for API calls you can create a global interceptor and return a response based on your status code to your component.
This would go in your main.js.
axios.interceptors.response.use(null, function(error) {
console.log(error);
if(err.response.status === 406){
//your code here.
}
return Promise.reject(error);
});
you can wrap your call in a try{} catch(e) {} to handle what happens after the error happens
but it is impossible to prevent the browser from showing the error in the console programmatically because of the potential risk that a script might misuse the errored requests to hide its activities from the user.
check_time(day,hour){
var fields = {};
fields.day = parseInt(day);
fields.hour = parseInt(hour);
try {
this.$http.post('courses/check', fields)
} catch {
this.$store.dispatch('alert', {'message': 'Already exist a course in this interval.'});
}
}

Alert() pops up twice in axios interceptor (Vue.js)

In my Vue app, I instantiate a single instance of axios and use it across the app for HTTP requests. I have set up a response interceptor which checks if any response from the backend is 401 unauthorized, and if so, shows an alert message. This basic flow has been implemented, but you need to hit "OK" on the alert message twice for it to go away, and I am not sure why.
Axios instance:
import axios, { AxiosError, AxiosInstance, AxiosResponse } from 'axios';
const axiosInstance: AxiosInstance = axios.create();
axiosInstance.interceptors.response.use(
(response: AxiosResponse) => response,
(error: AxiosError) => {
if(error.response && error.response.status === 401) {
alert('There has been an issue. Please log out and then log in again.');
return Promise.reject(error);
}
}
);
export default axiosInstance;
The request whose response is being intercepted:
import axiosInstance from 'axios-instance';
public async getloggedInUserId() {
await axiosInstance.get('/sessions.json')
.then((response) => {
if(response.data.user_id) {
this.SET_USER_ID(response.data.user_id);
}
});
}
I've read this thread, but my issue seems to be different: Javascript alert shows up twice
I've tried changing the return statement from return Promise.reject(error); to return false; but that did nothing for me.
As Phil suggested in the comment above, looking at at the Network tab in the browser console helped me solve the issue. The console showed how each component in the page was being loaded along with the resulting response code. In short, two processes were actually returning 401, which was the reason why the alert was being called twice.
I have decided to move the code that calls alert from a global axios interceptor (called whenever any process returns 401) to a .catch block inside one specific axios process, so that it only gets called once.
Your promise throws error in axios error interceptor, and error called second times.

Fetch still throws despite having catch block

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'); });

Angular 2 Http get not triggering

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...!

Categories

Resources