Angular 4 - Observable catch error
Asked Answered
F

4

29

How can I solve the problem of return with error, use the capture inside the Observable?

I want to execute a function inside the catch, to do some validation before the subscribe is executed.

Thank you in advance, thank you very much for your attention.

Error occurs in -> .catch( (e) => {console.log(e)} )

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) => {console.log(e)} );
    }
}

Error

ERROR in /XXXXXX/application/src/app/compare/service.ts (28,17): Argument of type '(e: any) => void' is not assignable to parameter of type '(err: any, caught: Observable) => ObservableInput<{}>'.
Type 'void' is not assignable to type 'ObservableInput<{}>'.

Footcloth answered 2/9, 2017 at 21:15 Comment(0)
C
34

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)
  }
}

Using Observable.throw() worked for me

Chrysler answered 2/9, 2017 at 22:33 Comment(0)
P
24

With angular 6 and rxjs 6 Observable.throw(), Observable.off() has been deprecated instead you need to use throwError

ex :

return this.http.get('yoururl')
  .pipe(
    map(response => response.json()),
    catchError((e: any) =>{
      //do your processing here
      return throwError(e);
    }),
  );
Philter answered 30/11, 2018 at 9:0 Comment(0)
P
16

catch needs to return an observable.

.catch(e => { console.log(e); return Observable.of(e); })

if you'd like to stop the pipeline after a caught error, then do this:

.catch(e => { console.log(e); return Observable.of(null); }).filter(e => !!e)

this catch transforms the error into a null val and then filter doesn't let falsey values through. This will however, stop the pipeline for ANY falsey value, so if you think those might come through and you want them to, you'll need to be more explicit / creative.

edit:

better way of stopping the pipeline is to do

.catch(e => Observable.empty())
Pareu answered 2/9, 2017 at 21:17 Comment(1)
Or just .catch(e => Observable.never()).Grooved
I
2

You should be using below

return Observable.throw(error || 'Internal Server error');

Import the throw operator using the below line

import 'rxjs/add/observable/throw';
Irreclaimable answered 2/9, 2017 at 21:23 Comment(3)
only if you want to pass the error through. If your goal is to truly handle / catch the error, then you shouldn't rethrow.Pareu
@Pareu elaborate please!Irreclaimable
Observable.throw() throws an error, so that the rest of the observable sequence skips and you go straight to the error handler of the subscriber. You can optionally not rethrow and just return an observable if this is not your intended behavior. It really depends on your use case.Pareu

© 2022 - 2024 — McMap. All rights reserved.