Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to throw observable error in angular http interceptor

I tried to throw an observable error in the interceptor and then handles this error. but I can't. When success is false, I can also receive successful subscribe.

I tried to return a value again in next.handle(restReq). But I failed and did not subscribe to anything

restApi return like this

{
  "success": false,
  "data": {
    "name": "Bad Request",
    "message": "123",
    "code": 0,
    "status": 400,
    "type": "yii\\web\\BadRequestHttpException"
  }
}

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/internal/Observable';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private sessionUrl = '/wechat/session';

  constructor(
    private http: HttpClient
  ) { }

  getSession(): Observable<any> {
    return this.http.post<any>(this.sessionUrl, {});
  }
}

auth.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '@core/services/auth.service';
import { interval } from 'rxjs/internal/observable/interval';
import { switchMap, take } from 'rxjs/operators';

@Component({
 selector: 'app-auth',
 templateUrl: './auth.component.html',
 styleUrls: ['./auth.component.scss']
})
export class AuthComponent implements OnInit {
  constructor(
    private authService: AuthService
  ) { }

  ngOnInit(): void {
    this.authService.getLoginQrcode()
      .subscribe(
        data => console.log(data),
        error => console.log(error);
  }
}

http-interceptor.ts

import { Injectable } from '@angular/core';
import {
  HttpErrorResponse,
  HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse
} from '@angular/common/http';

import { Observable } from 'rxjs';

@Injectable()
export class RestInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let baseUrl = environment.baseUrl + '/' + environment.version;
    let headers = req.headers;
    const restReq = req.clone({
      headers,
      withCredentials: true
    });

    return next.handle(restReq);
  }
}
like image 465
thanatos Avatar asked May 04 '18 18:05

thanatos


People also ask

What is error interceptor in angular?

What is an error interceptor? An error interceptor is a special kind of interceptor used for handling errors that happen when making HTTP requests. Errors come either from the client-side (browser) or the server-side when the request fails for some reason.

What is HTTP error response in angular?

A response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response.

How do you get httpErrorResponse?

Whenever the error occurs in an HTTP operation, the Angular wraps it in an httpErrorResponse Object before throwing it back. We catch the httpErrorResponse either in our component class or in the data service class or globally. The Global HTTP error handling is done using the Angular HTTP Interceptor.

Can angular have multiple HTTP interceptors?

After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.


1 Answers

Try doing this in your interceptor

return next.handle(request).map((event: HttpEvent<any>) => {
       if (event instanceof HttpResponse && event.body && !event.body.success) {
         throw new HttpErrorResponse({
                            error: 'your error',
                            headers: evt.headers,
                            status: 500,
                            statusText: 'Warning',
                            url: evt.url
                        });
       }
       return event;
    );
like image 181
Javier Solis Guzman Avatar answered Oct 03 '22 01:10

Javier Solis Guzman