angular - Angular handleError : How to get custom API error messages?

标签 angular api error-handling response

我正在尝试解决另一个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();
    }
  }

我的服务功能如下所示:
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'))
    );

  }

现在,我已经按照Angular文档中所述完全实现了用于错误处理的功能。我已经将该功能外包了,它看起来像这样:
handleError<T> (operation = 'operation', result?: T) {
    return (error: HttpErrorResponse): Observable<T> => {

      const userMessage = error.message;

      return throwError(userMessage);
    };
  }

但是如何访问API响应的主体? error.message始终未定义。我只能访问status代码和url。如果API返回不同于200的错误代码,如何访问响应正文?

非常感谢

最佳答案

您可以为此使用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");
    }
  }

关于angular - Angular handleError : How to get custom API error messages?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50944140/

相关文章:

javascript - 在没有angularfire的情况下以 Angular 6初始化firebase

angular - 如何从 angular-material2 对话框与其父级进行通信

javascript - 在 React 应用程序中访问 api 时出错

用于以通用方式返回序列的 C++ API

php - PHP : class display error function

Angular 7 : NullInjectorError: No provider for FormGroup

angular - AWS amplify Angular 自定义验证器组件

node.js - Node (Express) - 通过 api 使用 express 发送 pdf

python - 编写一个带数字并返回其对应月份缩写的基本程序

ios - 在 Swift 2 中使用 Alamofire 进行错误处理