Exception handling in angular 2

1

How to implement an external exception handling class and not do it in the following way and not repeat them in the different services. So that the alert is displayed by the client.

 return this.http.get(this.config.apiEndpoint + 'Values')
            .map(response => <person[]>response.json())
            .catch((error: any) => {
                if (error.status === 500) {
                    alert('Error 500');
                }
                else if (error.status === 400) {
                    alert('Error 400');;
                }
                else if (error.status === 409) {
                    alert('Error 409');;
                }
                else if (error.status === 406) {
                    alert('Error 406');;
                }
            });
    
asked by Erwing 29.03.2017 в 05:20
source

2 answers

1

Usually I have the functions of handling the errors and of capturing the data in a service that injects in the components or other services as required. The functions are these:

.- Try the mistakes:

public handleError (error: Response | any) {

let errMsg: string;
let errorCode:number;
if(!environment.production){
  console.log("(handleError) Error Arrojado:");
  console.log(error);      
}
if (error instanceof Response) {
  const body = error.json() || '';
  const err = body.error || JSON.stringify(body);
  errMsg = '${error.status} - ${error.statusText || ''} ${err}';
  errorCode = +error.status;
} else {
  errMsg = error.message ? error.message : error.toString();
}      
if(!environment.production)console.error(errMsg);
this._helper.notificationToast(errMsg,"Error","error");
if(errorCode===401){
    this._router.navigate(['salir']);
}
return Observable.throw(errMsg);

}

.- To extract the data I use:

public extractData(res: Response) {
let body = res.json();


if(!environment.production&&environment.depurar){      
  if(body.error){
    console.log("(extractData) Body Error:");
    console.log(body.error);
  }
}

//Actualizar token
if(body.token!=null){
  // if(!environment.production){console.log("Token actualizado: "+body.token)}
  this.token=body.token;
}

//Si ha habido un error lanzar mensaje
if(body.error){
  this._helper.notificationToast(body.error,"Error","error");
}

if(body.success&&!body.data){
    var data = {success:true, message:body.success}; 
    body.data=data;
}

return body.data || { };

}

and just like that is implemented in another service (Get a user profile):

getPerfil(perfilId:string): Observable<Perfil> {
    let _headers = new Headers({ 'Authorization': 'Bearer ' + this._autenticacionService.token });
    let _options = new RequestOptions({ headers: _headers });
    return this._http.get(environment.api_url+'/seguridad.php/perfil/'+perfilId, _options)
        .map((response: Response) => {
          return this._helperService.extractData(response);
        })
        ._catch(err=>this._helperService.handleError(err))
        ;
}
    
answered by 01.05.2017 в 12:00
0

If I understand what you are looking for, it is ErrorHandler

It could be something like this:

import { ErrorHandler } from "@angular/core";
import { NgModule } from "@angular/core";

export class MyErrorHandler implements ErrorHandler {

 handleHTTPError(res:Response){
     //Tratar error aqui
     throw new Error("error HTTP : "+ res.statusText +" ("+ res.status +")");
 }

}
@NgModule({
    providers: [{
                provide: ErrorHandler,
                useClass: MyErrorHandler
                }]
})
export class MyErrorModule {}

In your app.module

import { MyErrorHandler } from "./error.-module"; <- donde lo tenga
import { MyErrorModule } from "./error.-module";  <- donde lo tenga

//..

@NgModule({
           imports: [ MyErrorModule
           //..
           ],

           //..
           providers: [MyErrorHandler]

           //..
return this.http.get(this.config.apiEndpoint + 'Values')
            .map(response => <person[]>response.json())
            .catch((res)=>this.handleHTTPError(res));
            });

PS: I do not have much experience in Angular2, and I do not know if this is the best way to handle this situation, as angular2 is changing for example before it was called ExceptionHandler and I do not know if many details have changed for use it ect.

    
answered by 29.03.2017 в 10:08