How to print the error message in Angular?

Asked

Viewed 2,556 times

0

I am new as Angular programmer, I have been studying for a little while and I really need help to solve a problem in my Spring Boot project with Angular. I’m looking to print the Java API message on Angular.

I’m gonna take you step by step to make you understand.

Notice the figure below the Postman

inserir a descrição da imagem aqui

I’d like you to look at the records that already exist in the bank, my API Java can save records in the bank, but I created many business rules in the table Styles, I’ll show you one of the rules;

For example, the system does not allow the user to save a record that already exists in the database, if you observe in the figure above the first record is with the name of Amber Lager, and I’ll try to save the same record so you can see what happens.

That was the submitted record:

inserir a descrição da imagem aqui

Since the submitted record already exists in the database then the Java API triggers an error message as you can see below:

They would like to realize that there is the error message of the User and the Developer, what I need is the error message of the User represented as messaging and on it is written "Style name already registered"

inserir a descrição da imagem aqui

OBS: Java API is behaving as expected

The same thing happens on a Front-End screen, NOTEM, the message in red that is fired just below the screen.

inserir a descrição da imagem aqui

This error message was triggered by my API Angular, unfortunately I am inciante as Angular programmer, the message that should be sent would not be that of the figure below, had to be the message that is in the Java API as "Style name already registered", this error message as you can see in the figure below is a generic message, that is, my Angular API does not know how to distinguish the error messages, and because of this any error that appears in the system it will always send this error message from the figure below, because that’s exactly what I don’t want.

inserir a descrição da imagem aqui

This error message is configured in this file below:

import { Injectable } from '@angular/core';

import { ToastyService } from 'ng2-toasty';

@Injectable()
export class ErroHandlerService {

  constructor(private toasty: ToastyService) { }

  handle(errorResponse: any) {
    let msg: string;

    if (typeof errorResponse === 'string') {
      msg = errorResponse;
    } else {
      msg = 'Erro ao processar serviço remoto. Tente novamente.';
      console.error('Ocorreu um erro', errorResponse);
    }

    this.toasty.error(msg);
  }

}

Note that the same message that came out in Postman was also sent on the consoles of the internet browser as you can see in the figure below;

inserir a descrição da imagem aqui

I can find this similar code on the Github, watch:

REPOSITORY

import { Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { Response } from '@angular/http';

import { NotAuthenticatedError } from './../seguranca/money-http';
import { ToastyService } from 'ng2-toasty';

@Injectable()
export class ErrorHandlerService {

  constructor(
    private toasty: ToastyService,
    private router: Router
  ) { }

  handle(errorResponse: any) {
    let msg: string;

    if (typeof errorResponse === 'string') {
      msg = errorResponse;

    } else if (errorResponse instanceof NotAuthenticatedError) {
      msg = 'Sua sessão expirou!';
      this.router.navigate(['/login']);

    } else if (errorResponse instanceof Response
        && errorResponse.status >= 400 && errorResponse.status <= 499) {
      let errors;
      msg = 'Ocorreu um erro ao processar a sua solicitação';

      if (errorResponse.status === 403) {
        msg = 'Você não tem permissão para executar esta ação';
      }

      try {
        errors = errorResponse.json();

        msg = errors[0].mensagemUsuario;
      } catch (e) { }

      console.error('Ocorreu um erro', errorResponse);

    } else {
      msg = 'Erro ao processar serviço remoto. Tente novamente.';
      console.error('Ocorreu um erro', errorResponse);
    }

    this.toasty.error(msg);
  }

}

Although I got a good code template for me to help mimic the error message of the Java API in the Angular API I’m still having trouble.

Note again the error message:

inserir a descrição da imagem aqui

You may notice that below the Response has the "OK": false, just below has the status: 400, lower has the statusText: "OK", then comes the type: 2, then comes the url:"http://localhost:8080/styles", ultimately the _body: "[{"messaging":"Already registered style name","messaging":"com.algaworks.Brewer.service.Exception."}]

Then have the:

  1. OK
  2. status
  3. statusText
  4. type
  5. url
  6. _body

If I go to adapt the code found in the github repository on the internet with my project I can find in the code all except the _body, I was impressed by this, it really sucked, if I could access maybe I would be able to solve my problem.

====================================================

I tried to perform the check like this, but it generated error in type === 2

else if (errorResponse instanceof Response && errorResponse.type === 2){
      msg = 'Ocorreu um erro ao processar a sua solicitação';
    } 

================================================

Following the suggestion of Peter, putting

salvar(form: FormControl) {
    this.estiloService.adicionar(this.estilo)
    .then(() => {
      this.toasty.success('Cerveja adicionado com sucesso!');
      form.reset();
      this.estilo = new Estilo();
    })
    .catch(erro => this.erroHandler.handle(console.log(erro)));

gave this:

inserir a descrição da imagem aqui

plus that

inserir a descrição da imagem aqui

What I need is to somehow print the error message that comes from the Java API that is Style name already registered on the browser screen.

I’m sorry if I was too long in my explanation, but it was necessary.

This is my repository

2 answers

1


Dude you checked that condition if (typeof errorResponse === 'string') is true? You can copy the call code from the Errohandlerservice.Handle function

  • Pedro, it was not I who notified as negative in your suggestion, but it does not solve my problem.

  • It is because so, from what I understood shows the error warning but always with the msm message, would be in case the condition not being met, you would have to check if it is passing to the function only msg (which would be in the string type and would enter the condition) or the Response object

  • But if you notice in my code there is already this check, and if I am going to perform this check that you are suggesting I am performing an incorrect check, I need to somehow get the _body check or get a get in the java API message.

  • In fact you would not change the check, only on the return of the HTTP method you would pass only msg to the function Errohandlerservice.handle. You could copy the HTTP method that is called?

  • How would you do that?

  • Put the HTTP method to save a style, which I can exemplify.

  • 1

    Cara saw your repository here (now that I saw that you had put the link), was as I had said, in the "style-registration.component.ts" on line 39 you are passing the error object, in fact you would have to pass only to msg

  • Actually this suggestion you gave actually partially solves the problem, but it’s just a stopgap, because I have two other business rules on that same table, and if I put it fixed like you suggested I won’t be able to put the other messages according to the Java API business rule, it would have to be a get straight from the Java API picking up from _body to access the content of the Message Array. And if it gets fixed the message would be in a way also disabling the class error-Handler.services.ts

  • 1

    I didn’t understand it very well, but my suggestion would be this change .catch(erro => this.erroHandler.handle(erro)); for .catch(erro => this.erroHandler.handle(erro._body.mensagemUsuario));

  • for this form, for example, if the user presses 5 times consecutively the Submit in this form it triggers the exception configured in the class error-Handler.services.ts, but if the message has fixed in this form it will not return anything to the user, but trigger an error message on browser consoles that for the user does not serve

  • opa, calm down I’ll give a look! rs

  • This suggestion almost comes close, but did not solve, it triggered the standard message of the system, it was good that there was a way to put this code in that class error-Handler.services.ts

  • If you have not fired the message of the already registered style, gives a console.log(erro._body.mensagemUsuario) and check if it is right to access the message. You can only move this code to error-Handler.services.ts if you are sure that msg will always come on erro._body.mensagemUsuario, pq else you will have to add more code to suit a msg view of a different object.

  • because the error-Handler.services.ts class is managing all system errors it is impossible to generate messages on the.log console, but I still tried and generated the error message "There was a Undefined error"

  • in addition to generating the default system message.

  • 1

    The console.log(erro._body.mensagemUsuario) is in the style-register.component.ts, something like that .catch(erro => {console.log(erro._body.mensagemUsuario);this.erroHandler.handle(erro._body.mensagemUsuario));}

  • unfortunately did not take!

  • 1

    Right I saw here that your _body is an array so try this .catch(erro => {console.log(erro._body[0].mensagemUsuario);this.erroHandler.ha‌​ndle(erro._body[0].mens‌​agemUsuario));}

  • generated an error but in resume gave it here "ERROR Error: Uncaught (in Promise): Typeerror: Cannot read Property 'messaging' of Undefined Typeerror: Cannot read Property 'messaging' of Undefined"

  • At some point these tests appeared on the console the correct msg? If it has not appeared you will have to give a console.log(erro) and inspect how to properly access msg and pass through Handle

  • i updated the post take a look please.

  • 1

    try this guy .catch(erro => this.erroHandler‌​.ha‌​ndle(erro.json().mensagemUsuario))

  • did not work, unfortunately.

  • 1

    Check the console .catch(erro => {&#xA; console.log(erro.json().mensagemUsuario);&#xA; this.erroHandler‌​.ha‌​ndle(erro.json().mensagemUsuario))&#xA;})

  • gave Undefined error message.

  • Guy returns the "style-registration.Component" the way you did before and in "error-Handler.service.ts" puts this: handle(errorResponse: Response) {&#xA; let msg: string;&#xA; let errorMsg: string = errorResponse.json()[0].mensagemUsuario;&#xA;&#xA; if (typeof errorMsg === 'string') {&#xA; msg = errorMsg;&#xA; } else {&#xA; msg = 'Erro ao processar serviço remoto. Tente novamente.';&#xA; console.error('Ocorreu um erro', errorResponse);&#xA; }&#xA;&#xA; this.toasty.error(msg);&#xA; }

  • I will consider it as correct, but you helped me a lot to find the solution, I will shit the solution here, because I found how to solve, thanks to you and a group of my colleagues, all right?

  • 1

    Ball show, the important thing is you have gone after and thought of a response.

Show 23 more comments

0

The change has to be made only in the add method in the file styled.service.ts with this change the error manager is responsible in gives a get on the error message of the Java API, it had already been configured for that same.

adicionar(estilo: Estilo): Promise<Estilo> {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
        return this.http.post(this.estilosUrl,
        JSON.stringify(estilo),  { headers })
      .toPromise()
      .then(response =>  response.json())
      .catch( response => {
          if ( response.status === 400 ) {
              const responseJson = response.json();
              if ( responseJson[0].mensagemUsuario === 'Nome do estilo já cadastrado' ) {
                  return Promise.reject('Nome do estilo já cadastrado');
              }
          }
          return Promise.reject (response);
      });
   }

After the modifications performed worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.