如何处理响应对象中的错误

时间:2019-06-06 15:11:28

标签: javascript angular rest api error-handling

在应用程序中,使用错误的用户名或密码登录时,会向我发送一个错误对象作为响应。

POST https://abcdserver.zxcv.com/abcdserver/connect/token 400 (Bad Request)
Error performing password flow 
HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request", url: "https://abcdserver.zxcv.com/abcdserver/connect/token", ok: false, …}

如何处理这些错误。这是我的代码

login.component.ts

jwtHelper: JwtHelper = new JwtHelper();
  this.authService.loginOrg(this.userCredential.email, this.userCredential.password).then((resp) => {
    let token = resp['access_token'];
    if (token === null) {
      this.invalidLogin = true;
    }
    let decodedToken = this.jwtHelper.decodeToken(token);
    this.UserId = decodedToken.userid;
  }, (reason) => {
    this.invalidLogin = true;
  });

authservice.component.ts

import { OAuthService } from 'angular-oauth2-oidc';    
public loginOrg(userName: string, password: string) {
        return this.oAuthService.fetchTokenUsingPasswordFlow(userName, password);
    }

1 个答案:

答案 0 :(得分:0)

有2个选项:
1)实现ErrorHandler(https://angular.io/api/core/ErrorHandler)来处理应用程序中生成的所有错误,或者
2)像这样处理您的http调用中的每个错误:
        this.getMEthod()。subscribe(resp => {您的逻辑此处},错误=> {您的逻辑此处})