Home > Enterprise >  Why an Observable doesn't catch any error?
Why an Observable doesn't catch any error?

Time:09-02

I have a problem with some Observable and error handling. I have to make a call to an API for deleting a resource, but if this resource is used from some other element the DB send an error back.

I've used the try-catch statement too, but it doesn't work.

That's the function:

        try {
          this.itemService.delete(this.item).subscribe(
            val => console.log('val:', val),
            err => console.log('err:', err),
            () => this.router.navigate(['items/'])
          );
        } catch (e) {
          console.log('error from catch:', e);
        }
      }

The delete function in the itemService just takes the item, fetch the ID from it and make an http request that replies with an Observable.

If I try to delete an unused item it works perfectly: the "val: ..." is in the console and finally it sends me to the "items/" page.

But if the db replies with an error because the item is used, I expected to see "err: ..." or "error from catch: ..." in the console. But I only receive the DB error from the backend.

That's the response from my backend:

{"statusCode":400,"message":"Can't delete Item de1b8d07-xxx: Item de1b8d07-xxx contains nested dependencies, please remove all dependencies first and then remove this Item again.","error":"Bad Request"}

Why it can't understand the error and show me the "err:" or "error from catch:"?

Where am I wrong?

Thanks in advance!

Edit after Vivek kushwaha reply:

I tried this too:

this.a = this.itemService.delete(this.item);

        this.a.pipe(
          catchError(err => {
            console.log('catcherror:', err);
            return throwError(err);
          })
        )
          .subscribe(
            res => console.log('HTTP response', res),
            err => console.log('HTTP Error', err),
            () => console.log('HTTP request completed.')
          );

But nothing changes: when it works it replies with "HTTP response ...", but when the backend replies with an error nothing happens in the console but the DB error.

CodePudding user response:

try catch block won't work here, unless there is a system exception. Try to use pipe and catchError operator from rxjs.

Or you could use tap operator from rxjs to debug the error.

Also, check if you are using http interceptor in the application, which might be intercepting the delete request and handling the error

CodePudding user response:

If you want to use the catch() of the Observable you need to use Observable.throw() method before delegating the error response to a method

import { Injectable } from '@angular/core';
import { Headers, Http, ResponseOptions} from '@angular/http';
import { AuthHttp } from 'angular2-jwt';

import { MEAT_API } from '../app.api';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class CompareNfeService {


  constructor(private http: AuthHttp) {}

  envirArquivos(order): Observable < any > {
    const headers = new Headers();
    return this.http.post(`${MEAT_API}compare/arquivo`, order,
        new ResponseOptions({
          headers: headers
        }))
      .map(response => response.json())
      .catch((e: any) => Observable.throw(this.errorHandler(e)));
  }

  errorHandler(error: any): void {
    console.log(error)
  }
}

CodePudding user response:

You are not throwing error from your API, You are sending Ok({YourObject}).

You need to send 404/error from your API or need cast your response object and manually check the error information like.

`this.yourservice.delete(this.item).subscribe(
        res => {
         if(res.statusCode==400){
              // here is your error..    
            }
},
        err => console.log('HTTP Error', err),
        () => console.log('HTTP request completed.')
      );`
  • Related