I've been getting into angular recently and I would like to know what is the best way to capture and display the errors I receive from a REST API server, I have the following:
Service
import { Injectable } from '@angular/core';
import { Usuario } from 'src/app/models/usuario.model';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class UsuarioService {
constructor(public _http: HttpClient) {}
crearUsuario( usuario: Usuario){
let url = `http://localhost:3000/usuario`;
return this._http.post(url, usuario);
}
}
Component
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { UsuarioService } from '../services/service.index';
import { Usuario } from '../models/usuario.model';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./login.component.css']
})
export class RegisterComponent implements OnInit {
forma: FormGroup;
constructor( public _usuarioService: UsuarioService) { }
ngOnInit() {
this.forma = new FormGroup({
// Valor por defecto y validaciones
nombre: new FormControl('test', Validators.required ),
correo: new FormControl('[email protected]', [Validators.required, Validators.email]),
password: new FormControl('123456', Validators.required),
confPassword: new FormControl('123456', Validators.required),
condiciones: new FormControl(true)
}, { validators: this.verificarPassword('password', 'confPassword')});
}
verificarPassword( campo1: string, campo2: string){
return ( group: FormGroup) => {
let pass1 = group.controls[campo1].value;
let pass2 = group.controls[campo2].value;
if( pass1 === pass2 ) return null;
return {
sonIguales: true
}
}
}
registrarUsuario(forma: FormControl){
console.log(forma);
let usuario = new Usuario(
this.forma.value.nombre,
this.forma.value.correo,
this.forma.value.password
)
this._usuarioService.crearUsuario(usuario).subscribe( result =>{
console.log(result );
});
}
}
The error returned is a status 500
if there is a failure in the registration and a status 200
if the request is successful.
What I want to do is give the user more clarity when creating the account, showing where the error comes from, in this case it would be because the email already exists.
first of all, Thanks :)
In your service's subscribe, the second parameter is an error callback , as @AlexisNarvaez says, the strategy you choose to display the error in the view is up to you.
Then when receiving your error you can handle it in the way you prefer, I generally do it similar to the previous example, but using a single variable, I create a variable in the component eg: public messageError that is undefined at the moment
Then in the HTML, you can do the following:
The ngIf says to show the error as long as it exists and if it exists it shows the error, I use the same variable
So in the subscribe error you do the following:
The best way to do this is with an interceptor https://angular.io/api/common/http/HttpInterceptor
The main function of the interceptor is to intercept all http/https requests that are made through the web. This way I don't have to worry about capturing errors on every subscription I make.
In my case I use a store to store the errors and I am subscribed to that error store with an error notification component (Snackbar Material).
I leave you an example of the case in question
In my case, I showed the error of the requests at the time of making the request and that the token was no longer in validation, you can adapt my code to yours to the error that you want to show, which would be the same.
TS AND HTML.