Search code examples
angularangular-errorhandler

update component with custom error handling in angular 6


I'm using Angular 6.

I have created a custom Error Handler extending ErrorHandler to handle all network errors like.

import {ErrorHandler, Injectable, Injector} from '@angular/core';
import {HttpErrorResponse} from '@angular/common/http';
import {Router} from '@angular/router';
import {ErrorsService} from '../errors-service/errors.service';
import {ToastrService} from 'ngx-toastr';

@Injectable()
export class ErrorsHandler implements ErrorHandler {

  constructor (
    private injector: Injector,
    private toastr: ToastrService
  ) {}

  handleError(error: Error | HttpErrorResponse) {

    const errorsService = this.injector.get(ErrorsService);

    const router = this.injector.get(Router);

    if (error instanceof HttpErrorResponse) {
      if (!navigator.onLine) {
        // Handle offline error

      } else {
        // Handle HTTP Error
        console.log('Http Error occurred');
        errorsService.log(error);

        if (error.status === 403 || error.status === 401) {
          // Clear credentials to login again
          router.navigate(['/auth/logout']).then();
        }

        if (error.status === 400) {
          if (error.error !== null) {
            // Handle 400 errors
            // Generally validation error.
          }
        } else if (error.status === 404) {
          // resource not available
          message = 'Requested resource does not exists';
        } else {
          // handle other type of errors
          message = `${error.status} - ${error.message}`;
        }

      }
    } else {
      // Client Error Happened
      // Send the error to the server and then
      // redirect the user to the page with all the info
      console.log('Not HttpError occurred');
      errorsService.log(error);
    }
  }
}

This handler handles all errors as expected. But in the component's HTML, submit button is disabled on the status of submitted like

export class SignupComponent implements OnInit {

  form: FormGroup;
  submitted = false;

  constructor(
      private fb: FormBuilder,
      private auth: AuthService
  ) { }

  ngOnInit() {
    // Initialize form
    this.form = this.fb.group({});
  }

  /**
   * Submit form
   */
  onSubmit() {
    this.submitted = true;

    if (this.form.invalid) {
      this.submitted = false;
      return;
    }

    this.auth.register(this.form.value).subscribe(
        () => {
          // Handle success 200 response
          this.submitted = false;
        }
    );
  }
}

In the above case, onSubmit() make a request to the service and subscribe to it.

I want to reset submitted flag to false after the request/response is complete. It is easy to handle success response and reset submitted flag. But since errors are handled by the custom error handler, how can I reset submitted flag?

If I put error handling in the component then custom error handler stops working. Also if I avoid using custom error handler then I will have to write repeated code in every subscription to handle all type of errors like 403, 404, 500, etc.


Solution

  • Assuming you are using rxjs 6, perhaps you could use finalize which runs after error/success happens, so something like this:

    this.auth.register(this.form.value).pipe(
      finalize(() => this.submitted = false)
    )
    .subscribe(() => {
      // handle succecss 200 response
    })