javascript - 如何处理响应对象中的错误
问题描述
在应用程序中,当使用错误的用户名或密码登录时,它会向我发送一个错误对象作为响应。
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);
}
解决方案
有 2 个选项:
1) 实现 ErrorHandler ( https://angular.io/api/core/ErrorHandler ) 来处理应用程序中生成的所有错误,或者
2) 像这样处理 http 调用中的每个错误
: getMEthod().subscribe(resp =>{ 你的逻辑在这里},错误 =>{ 你的逻辑在这里})
推荐阅读
- python - 如何访问 OpenCV 连接组件标签中的单个标签
- excel - 在单元格中强制使用美国货币(或其他国家/地区)
- nasm - ErrCode:139 上的 Assembly Nasm x86_64 Coredump
- angular - amcharts 4 光标和鼠标定位不正确
- python - 在 pandas.groupby 之后删除重复值
- c - 为什么许多窗口的窗口创建速度很慢?可以更快吗?
- permissions - Xcode 11.3 没有在我的所有项目上打开 Assets.xcassets 文件
- android - LiveData 不会将类型推断为所需的返回值
- c++ - 删除类成员的动态分配内存的最佳方法是什么
- excel - 在 VBA 中识别 UI 自动化中的元素