Maybe I don't understand it, but if I have a service and I catch any error from it, how come zone.js
is throwing 404 not found, while I catch the error and also returning json object so the client will know what to do. How can I avoid that error in the console? Can I?
For example:
return this.http.post(this.callUrl, requestBody)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || { };
}
private handleError (error: Response | any) {
let body = error.json();
return Observable.throw(body);
}
The problem is that your handleError
function, the function you are passing to catch
does not handle the error, it actually transforms the error into a new error and propagates that (fails with it). The purpose of Observable.prototype.catch
is to handle errors and the purpose of Observable.throw
is to create them. This error is then returned to introduce a failure in the resulting stream.
Here is what your code would look like using a normal Http interface
async performPostRequest(requestBody) {
try {
await response = this.http.post(this.callUrl, requestBody);
return this.extractData(response);
} catch (error) {
handleError(error);
}
}
function handleError(error) {
const unwrappedError = error && typeof error.json === 'function'
? error.json()
: error;
throw unwrappedError;
}
I see in the comments a discussion of what capabilities Angular 2 supports for handling http errors. It supports all of the cases you likely require, including handling 404 errors, but their documentation is very bad. All of their http examples, and most of their examples in general, have too much code.
When I say, too much code, I mean it in the sense that they are full of more code than you should write and a lot of code you should not be writing at all.
You pasted something very close to their default error handler from their tutorial in this question, without noticing the behavior.
You should never do this obviously!
But in all seriousness, why do they handle all of the errors in all of their examples? Errors should always be unhandled by default so that they propagate up the stack and cause failure where they must.
To make a rule of always catching and rethrowing is a terrible practice.
If you want a generic error handler, it definitely does not belong in every service that consumes the source of a potential error, that is madness, but if you follow the examples, that is what you will end up with. Hundreds of lines of repeated, unmaintainable boilerplate that the next person who works on the project will have to slog through to understand your business logic.
Also, you should not pass unbound methods as callbacks as you do in your example but that is a separate conversation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With