首页 > 解决方案 > 如何处理响应对象中的错误

问题描述

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

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, …}

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

登录组件.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);
    }

标签: javascriptangularrestapierror-handling

解决方案


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


推荐阅读