He estado tratando de manejar una respuesta de error de mi API.
Lo que estoy tratando de conseguir:

Lo que realmente estoy recibiendo:

mi servicio.ts:
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { environment } from 'src/environments/environment'; import { map, catchError } from 'rxjs/operators'; import { Observable, throwError } from 'rxjs'; private url = environment.urlServer; constructor( private httpClient: HttpClient ) { } guardarUsuario( data: {nombre: string, correo: string, pass: string, descripcion: string }) { return this.httpClient.post(`${ this.url }/usuario`, data).pipe( catchError((res: HttpErrorResponse) => { console.log(res); return throwError(JSON.stringify(res)); }) ); }mi componente.ts:
this.coreService.guardarUsuario( data ) .subscribe( res => { console.log('Successfull response: ', res); }, err => { console.log('Error response', err); } );Actualización: Aquí está el código del interceptor
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { ToastrService } from 'ngx-toastr'; @Injectable({ providedIn: 'root' }) export class AuthInterceptorService implements HttpInterceptor { constructor( private toastr: ToastrService ) { } intercept( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> { const token: string = sessionStorage.getItem('token'); let request = req; if ( token ) { request = req.clone({ setHeaders: { 'Authorization': `Bearer ${ token }`, 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true' } }); } return next.handle(request).pipe( catchError((err) => { if (err.status === 401) { this.toastr.error(`Error: ${ err }`) } throw throwError( 'Auth error: ', err ); }) ); } } Esta es la primera vez que trabajo con interceptores, el interceptor ya está importado en los proveedores de app.module también. ¿Cómo puedo obtener el mensaje de error de mi respuesta API en el controlador de errores de mi suscripción?
¿Está utilizando el throwError correcto, no parece estar importado en su código, por ejemplo?
import { throwError } from 'rxjs'; Además, generalmente necesita extraer el mensaje de HttpErrorResponse , algo como:
return throwError(res.error.message); Hay un error en el interceptor : throw throwError(..) debería ser return throwError(...)
Si le sirve de algo a alguien, cambié el catchError del interceptor de:
catchError((err) => { if (err.status === 401) { this.toastr.error(`Error: ${ err }`) } throw throwError( 'Auth error: ', err ); })para:
catchError((error: HttpErrorResponse) => { let errorMsg = ''; if (error.error instanceof ErrorEvent) { errorMsg = `Error ${ error.error.message}`; } else { errorMsg = `Error code: ${error.status}, Message: ${error.message}` } return throwError(errorMsg); }) Y la httpRequest a:
guardarUsuario( data: {nombre: string, correo: string, pass: string, descripcion: string }) { return this.httpClient.post(`${ this.url }/usuario`, data);