Home > Blockchain >  Angular: How to throw an error inside an Observable
Angular: How to throw an error inside an Observable

Time:10-18

Despite looking at documentation, I am unclear how to throw an error within an if conditional with working with an Observable like so:

openCountrySearchDialog() {
   const addRef = this.dialog.open(DiscoverCountriesEntriyDialogComponent, {
      width: '600px',
      id: 'tid-known-countries-dialog-component',
      autoFocus: true,
      disableClose: true,
      data: []
   });
   addRef.afterClosed().subscribe(countries => {
      if (countries.length > 10) { 
          console.log("Oops, we got more than 10 countries");
      }
       this.countries = countries;
       this.changeDetector.detectChanges();
   });
}

I tried the following:

addRef.afterClosed().subscribe(
   (countries) => {
     this.countries = countries;
     this.changeDetector.detectChanges();
   },
   (error) => {
     if (this.countries.length > 10) {
       console.log('Oops, we got more than ten countries', error);
     }
   }
 )

I believe I have to use a pipe() but if so, I am not implementing it correctly:

addRef
   .afterClosed()
   .pipe(error => {
     if (this.countries.length > 10) {
       return error;
     }
   })
   .subscribe(countries => {
     this.countries = countries;
     this.changeDetector.detectChanges();
   });

CodePudding user response:

Simple version of this will be after you subscribe You can check res

if (this.countries.length>10) {
throw throwError(response);  
}

Import through error from rxjs and you will be able to catch your error

,
(error) => {
   console.log(error) 
 }

}

CodePudding user response:

A MatDialogRef afterClosed() does not throw errors. So, what you could do instead, is returning your ReturnObjects including error logic via the close() method.

// open dialog:
const dialogRef = this.dialog.open(DialogExample);
dialogRef.afterClosed().subscribe((result: DialogData) => {
  if (result.customResult === DialogResponse.ERROR) {
    // do error handling here with 'result.customBody'
    console.error('error response from afterClosed is: ', result.customBody);
  } else {
    // do success handling here with 'result.customBody'
    console.log('succes response from afterClosed is: ', result.customBody);
  }
});

export interfaces and enums:

export interface DialogData {
    customResult: DialogResponse;
    customBody: any;
}

export enum DialogResponse {
    SUCCESS = 'success',
    ERROR = 'error',
}

Dialog example:

// dialog-example.ts

@Component({
    selector: 'dialog-example',
    templateUrl: 'dialog-example.html',
})
export class DialogExample {
    constructor(
        public dialogRef: MatDialogRef<DialogExample>,
        @Inject(MAT_DIALOG_DATA) public data: DialogData
    ) {}

    public closeWithSuccess() {
        this.dialogRef.close(
            {
                customResult: DialogResponse.SUCCESS,
                customBody: 'all happy ;-)'
            }
        );
    }

    public closeWithFail() {
        this.dialogRef.close(
            {
                customResult: DialogResponse.ERROR,
                customBody: 'more than 10 countries do not exist on this planet, lolz'
            });
    }
}

and dialog html:

// dialog-example.html:
<button (click)="closeWithSuccess()">close with success</button>
<button (click)="closeWithFail()">close with fail</button>

Stackblitz

  • Related