问题
Here is my code in the httpService.ts
public HttpPost(url: string, data: any): Observable<Response>
{
let headers = new Headers();
let reqOpts = new RequestOptions();
headers.append(AUTH_CONTENT_TYPE_KEY, AUTH_CONTENT_TYPE);
if (this.Token) {
headers.append(AUTH_HEADER_KEY, AUTH_TOKEN_PREFIX + this.Token);
}
reqOpts.headers = headers;
return this.http.post(url, data, reqOpts).timeout(30000).map((res: Response) => res)
.catch((err: Response) => { return Observable.throw(err) });
}
If I try to using this service to call an API like this way:
this.httpService.HttpPost(url, data).subscribe(
(res: any) =>
{
// do something
},
(error: any) =>
{
if (error.status === 409)
// do something
else if (error.status === 401)
// do something
else
// do something
}
);
and if the res status code is one other than 200, such as 401, 403 or 409, then these kind of annoying errors are generated by zone.js in console. (sorry for hide part url of APIs)
So is there anyway to stop zone.js to generate such a kind of annoying errors in console, tried to google for a solution with example but not found yet, Thanks!
tried to use this in main.ts but not worked:
window.console.error = function() {};
Edit: add stack trace:
回答1:
When a network request fails, Chrome shows the error in the console. The error displays the url that failed, the HTTP status received and the origin of the request. Usually, in Angular, you're making an HTTP request in response to some action from the user. Angular captures those actions using zones, so, almost any error has its origin in zone.js
. If you check the whole stack trace, however, you'll see that the error happens after calls to your own code. It's just that is code in zone.js
what ends up calling that code.
So, the only way not to see request errors in the console, is to configure your chrome console to ignore them, but I don't think there is a programmatic way of doing so.
I'm sure you're thinking about window.onerror
, which in theory captures any uncaught exception. But those network errors are not JavaScript exceptions, so you won't be able to capture them.
I'd wouldn't replace console.error
. because if you do, you won't be able to see true errors you might have in your code. Anyway, as stated, in this case is Chrome who is writing to the console, and the only way to hide those errors is, as I already said, filtering them (but it'll only work for you, of course).
回答2:
In Dev mode, you can add the following line to import zone-error in src/environments/environment.ts
import `zone.js/dist/zone-error`;
Then most of zone related error stack trace will gone.
来源:https://stackoverflow.com/questions/49873128/how-to-stop-errors-generated-by-zone-js-in-browser-console