Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

362
Visualizações
Cannot get response from HttpClient

I have been trying to handle an error response from my API.

What I'm trying to get:

dev tools showing expected error message

What I'm actually getting:

console log showing observable object

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?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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(...)

over 4 years ago · Santiago Trujillo Relatório

0

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);
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda