1
The catchError operator is not intercepting back-end errors. For example, in the back end I do an email check and return an exception if the email already exists, as below:
public Usuario insert(Usuario usuario) {
if (usuarioService.findByEmail(usuario.getEmail()) == null) {
usuario = getRepository().save(usuario);
return usuario;
}else {
throw new DataIntegrityException("Email já está em uso");
}
}
However, on the front end in Angular 7, in my service method, the exception is not intercepted and the application redirects me to the main screen, preventing a proper handling and feedback of the error. Follows service code:
@Injectable
export class UsuarioService{
url: string = `${API_CONFIG.baseUrl}/usuarios`;
usuariosChanged = new EventEmitter<Observable<Usuario[]>>();
constructor(private http: HttpClient){
}
findAll(): Observable<Usuario[]>{
return this.http.get<Usuario[]>(${this.url});
}
findById(id: number): Observable<Usuario>{
return this.http.get<Usuario>(`${this.url}/id/${id}`);
}
post(usuario: Usuario): Observable<Usuario>{
return this.http.post<Usuario>(this.url, usuario)
.pipe(
tap(data => this.usuariosChanged.emit(this.findAll())),
catchError(this.handleError))
}
private handleError(error: any) {
let erro = error.message || 'Server error';
console.error('Ocorreu um erro', error);
return Observable.throw(erro);
}
}
And excerpt from the Component:
onSave(){
this.usuarioService.post(this.form.value)
.subscribe(data => {
this.notificationService.notify("Usuário salvo com sucesso!");
},
error => {
alert("Ocorreu um erro ao salvar!");
});
}
I still have an Httpinterceptor. My requests go through it, but if they are in error, they are not captured by the catcher either. Follows the code of the Interceptor:
@Injectable()
export class ErrorInterceptor implements HttpInterceptor{
constructor(){
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
return next.handle(req).pipe(catchError(err => {
const error = err.error.message || err.statusText;
return throwError(error);
}))
}
}
export const ErrorInterceptorProvider = {
provide : HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true,
};
What is the status of your error request?
– Eduardo Vargas
In the above code I am returning the status 400. But I have already forced a 404 for example and had the same behavior.
– Saulo Grego