Angular handleError:如何获取自定义API错误消息?

时间:2018-06-20 08:54:59

标签: angular api error-handling response

我正在尝试解决另一个Angular问题-您能帮我吗?在我的组件中,我有一个登录功能-像这样:

@RestControllerAdvice 
public class ExceptionHandlerRest{
 private Logger logger=LoggerFactory.getLogger(getClass());

 @ExceptionHandler(Exception.class)
 public ResponseEntity<?> handleException(Exception ex){
  logger.error("System Error", ex);
  SimpleResponse=new SimpleResponse(ex.getMessage(),"Error code 001"));
  return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
 }

}

我的服务功能如下:

public class SimpleResponse{
   String technicalMessage,userMessage;

   //public getters and setters


}

现在,我已经完全按照Angular文档中的描述实现了用于错误处理的功能。我已经将该功能外包了,看起来像这样:

    onLogin() {
    if (this.loginForm.valid) {
      const email = this.loginForm.get(['email']).value;
      const password = this.loginForm.get(['password']).value;

      this.ls.login(email, password).subscribe(
        result => {
          this.saveToken(result);
        },
        error => {
          this.errorMessage = error;
          this.loginForm.reset();
        }
    );

    } else {
      this.updateErrorMessage();
    }
  }

但是如何访问API响应的正文? login(email: string, password: string): Observable<string> { const apiUrl = environment.apiHostLumen + '/admin/login?email=' + email + '&password=' + password; const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }); const options = new RequestOptions({ headers: headers }); return this.http.get(apiUrl, options).pipe( retry(3), map(res => res.json()), map(data => { return data.token; }), catchError(this.ehs.handleError('login')) ); } 始终是不确定的。我只能访问handleError<T> (operation = 'operation', result?: T) { return (error: HttpErrorResponse): Observable<T> => { const userMessage = error.message; return throwError(userMessage); }; } 代码和error.message。如果API返回的错误代码与status不同,该如何访问响应正文?

非常感谢

3 个答案:

答案 0 :(得分:1)

您可以为此使用HttpInterceptor。由此,您可以在一个类中处理所有http错误。您可以在官方角逐中阅读更多关于Intercepting requests and responses的信息。

通过使用intercept方法,您可以拦截每个请求和响应。

 public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next
      .handle(req)
      .pipe(catchError(err => {
        if (err instanceof HttpErrorResponse) {
          this.onError(err);
        }
        return throwError(err);
      }));
  }



 private onError(response: HttpErrorResponse): void {
    const status: number = response.status;
    const serverErrorMessage = response.error;

    switch(status) {
      case 400:
        console.log("Bad request"); //or you can print the serverErrorMessage
      case 404:
        console.log("Not found");
    }
  }

答案 1 :(得分:1)

您可以执行error.error,这应该会给您来自服务器的错误响应。

handleError<T> (operation = 'operation', result?: T) {
    return (error: HttpErrorResponse): Observable<T> => {

      const userMessage = error.error; // should give error body

      return throwError(userMessage);
    };
}

来源:

https://angular.io/api/common/http/HttpErrorResponse

Accessing HTTP Error Response Body from HttpInterceptor in Angular

答案 2 :(得分:1)

我发现了错误。非常感谢您的帮助!我将错误类型重命名为linkGen,并使用pageGen实际上可以正常访问响应正文。我不知道该怎么忽略...

谢谢!看来可行!

相关问题