How should i catch and handle 406 error in VUEJS - javascript

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

Related

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

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

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

Clarifying "400 - Bad Request"

I am triggering a bad request on purpose from my backend. The backend using express is answering properly as expected with:
[...]
.catch((error) => {
res.statusCode = 400;
res.json({
msg: "This is some error",
err: error,
});
});
My question is: Is the 400 always showing up in browser console? I thought I handled the error the right way.
And why do I have to retrieve the data in the frontend with
// 400:
function (data) {
var data = data.responseJSON.msg);
}
instead of (similar to 200:)
// 400:
function (data) {
var data = data.msg);
}
I am just wondering, if I do something wrong.
Thanks for any advice
When fetching data asynchronously, any response other than a 2** response code gets handled by a .catch block. So any other response whether it be 4** or 5** gets caught by the catch block and for that reason if you're using a library like Axios or the likes the response from the backend will be in the error.response or data.response in your case.
I wasn't aware of what you're using to carry out the asynchronous fetching of data i.e. Fetch Api so my answer is a generic response and also is the above code complete?
In my experience any error from whatever weither it be am asynchronous call that generates an error always gets logged to the console, but you can from the front end handle those errors in the catch block
The problem is when the console.log tries to output the error, the string representation is printed, not the object structure, so you do not see the .response property or in your case the .responseJSON
By catching your error with an catch block .catch() or if you using async / await you should, usually, wrap the code inside of an try / catch to catch the error otherwise it will always output this red error in the console

Angular's subscribe not logging full error

I'm trying to log an error from a subscribe, but the error seems... incomplete?
I've never seen this kind of problem, nor could I find anything on Google. The code is the following:
this._http.post(this.urlPath, email).subscribe(
res => {
// stuff
},
err => {
console.log(err) // <- I need to log this
}
);
It works to an extent. When I open the browser's console, in order to check the error, what I get is this:
The thing is, it seems like there's missing information here. If I open the Network tab, the response for this same request looks like this:
As you can see, the real response has more information. I've tried using {observe: "response"}, but to no avail. I should note that if I try using fetch, the response comes complete, but I'd rather use HttpClient.
What is going on here?
When you receive a http error status code you can't access to the payload returned by the service by the same way that in a success case. Is like an special object.
But you can acccess to it doing some like this, using a pipe in your service and an error handler. This is a minimal example of it:
your.service.ts
...
handleError(error) {
return throwError(error.error);
}
return this.http.get ... the rest of your request.pipe(
catchError(this.handleError)
);
...
And where you consume your service, in err you can acces to full response that your error request contains.
...
, error => {
console.warn(error);
}
Or better than, you can throw the entire object to access to the error (response body) and the rest of params, like status code.

How to handle can-connect errors correcly when connecting to a RESTful API

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?

Categories

Resources