Reputation: 501
I have been trying to handle an error response from my API.
What I'm trying to get:
What I'm actually getting:
my service.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));
})
);
}
my component.ts:
this.coreService.guardarUsuario( data )
.subscribe( res => {
console.log('Successfull response: ', res);
}, err => {
console.log('Error response', err);
}
);
Update: Here´s the interceptor code
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 );
})
);
}
}
This is my first time working with interceptors, the interceptor its already imported in the providers of the app.module
too.
How can I get the error message from my API response in the error handler of my subscription?
Upvotes: 1
Views: 2704
Reputation: 501
If its any use to someone i changed the catchError
of the interceptor
from:
catchError((err) => {
if (err.status === 401) {
this.toastr.error(`Error: ${ err }`)
}
throw throwError( 'Auth error: ', err );
})
to:
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);
})
And the httpRequest
to:
guardarUsuario( data: {nombre: string, correo: string, pass: string, descripcion: string }) {
return this.httpClient.post(`${ this.url }/usuario`, data);
Upvotes: 1
Reputation: 12357
Are you using the correct throwError
, it doesn't seem to be imported in your code e.g.
import { throwError } from 'rxjs';
Also, you generally need to extract the message from the HttpErrorResponse
, something like:
return throwError(res.error.message);
There's a mistake in the interceptor: throw throwError(..)
should be return throwError(...)
Upvotes: 1