Search code examples
angularrxjsobservablehttpclientformbuilder

How to deal with http code errors filling select options with observables


I filling some select options with observables by calling web services. The point is I am trying to get the http code errors in order to hide the form (if any of these the http code is different to 200) and show a message to the user.

Can someone suggest me a good practice to do this?

Thanks in advance!

Repo: https://github.com/jreategui07/testing-subscriptions-form

Mock server runs with: mockserver -p 8080 -m mock

GET.mock

HTTP/1.1 400 Bad Request
Access-Control-Allow-Origin: *
Content-Type: text/plain; charset=utf-8
Connection: keep-alive

[
   { "error": "c1", "error_des": "any error" }
]

Solution

  • You can add an error handler to all of your select observables. Notice in this I am only gathering the last error and hide the form so if there are multiple error you can use an array to the formHasError variable.

    • Define a variable which will track the formErrors:
    formHasError: string[] = [];
    
    • Create an error function to handle the error
    import { catchError } from 'rxjs/operators';
    errorFn = catchError(e => {
      const err = e && e.error && e.error[0] && e.error[0].error_des;
      if(err){
        this.formHasError.push(err);
      }
      return [];
    });
    
    • In your component the select observables are modified to
    this.colorSC$ = catalogueService.getColors().pipe(this.errorFn);
    this.brandSC$ = catalogueService.getBrands().pipe(this.errorFn);
    this.sizeSC$ = catalogueService.getSizes().pipe(this.errorFn);
    this.fruitSC$ = catalogueService.getFruits().pipe(this.errorFn);
    
    • In your template add formHasError
    <form (ngSubmit)="onSubmit()" [formGroup]="anyForm" *ngIf="!formHasError.length">
    ...
    </form>
    <div class="error" *ngIf="formHasError.length">
      Form has some errors: 
      <p *ngFor="let err of formHasError">{{err}}</p>
    </div>