I want to inform the user if an HTTP request fails, without having to write additional code for every HTTP request.
I had a working prototype for angular 2:
@Injectable()
export class MyErrorHandler extends ErrorHandler {
constructor() {
super(false);
}
handleError(error: any) {
this.tellUser(error);
super.handleError(error);
}
tellUser(error: any) {
// dig for the root cause
if (error.rejection) {
error = error.rejection;
}
if (error instanceof ViewWrappedError) {
error = error.originalError;
}
let message;
if (error instanceof Response) {
// TODO: localize and display nicely
const messages = {
0: "Could not connect to server",
}
message = messages[error.status] || ("The server reported a system error (HTTP " + error.status + ")");
} else {
message = "A system error occurred.";
}
console.warn(message);
}
}
but the ViewWrappedError has been replaced in Angular 4 by
export function viewWrappedDebugError(err: any, context: DebugContext): Error {
if (!(err instanceof Error)) {
// errors that are not Error instances don't have a stack,
// so it is ok to wrap them into a new Error object...
err = new Error(err.toString());
}
_addDebugContext(err, context);
return err;
}
Which, by virtue of invoking toString on the HttpResponse, makes it hard to query the status code ...
I'd have expected angular to provide a public, well supported API for centralized error handling. Is there really no way to centrally handle HTTP errors other than parsing error messages?
Update: I'd prefer if a component could easily override the centralized error handling.