Let's say I sent a post
request to the server to create a user. If the server responds with an error, I want to get the body(form) I submitted(attached to that request) from the ErrorHandler
. The reason for this is that, for example, when the "create user" fails, I want to show a notification with some details taken from the form and a button to redirect you back to the respective page with the fields populated again with the retrieved form.
This is how my ErrorHandler
looks like:
@Injectable()
export class ErrorsHandler implements ErrorHandler {
constructor(
private injector: Injector,
) { }
handleError(error: Error | HttpErrorResponse) {
const errorsService = this.injector.get(ErrorsService);
const router = this.injector.get(Router);
const zone = this.injector.get(NgZone);
if (error instanceof HttpErrorResponse) {
// Server error happened
if (!navigator.onLine) {
return console.log('No Internet Connection.');
}
else if (error.status === HttpStatus.UNAUTHORIZED) {
console.log('ErrorsHandler handled HttpStatus Unauthorized. Navigating back to \'/login\' page.');
zone.run(() => router.navigate(['/login']));
}
else {
// Http Error
//How do I get the form from here? I need it for user notification.
return console.log('%c SERVER ERROR ', 'background: #222; color: #ff6961 ; font-size: 15px; border: 2px solid #ff6961;', error);
}
} else {
// Client Error Happend
// Send the error to the server and then
// redirect the user to the page with all the info
errorsService
.log(error)
.subscribe(errorWithContextInfo => {
router.navigate(['/error'], { queryParams: errorWithContextInfo });
});
}
}
}
First of all, you must confirm BE return JSON error in body. Next step you can custom HttpInterceptor for your idea, more details you can search by keyword angular httpinterceptor.
It is my source for HttpInterceptor, there may be some help.
and please setup the HttpInterceptor to app.module.ts
Let me know is it ok for you or not :)