【发布时间】:2018-01-14 11:44:56
【问题描述】:
我有一个登录功能,我想捕获服务器启动的异常并将它们冒泡到带有错误消息的视图中。到目前为止,我使用promise 处理异步部分,并且我想使用catch() 部分来捕获我的异常。问题是 handler 函数永远不会被调用,我在浏览器控制台中得到错误。到目前为止,这是我的代码,非常基本:
login(username: string, password: string): Promise<User> {
return this.http
.get(this.loginUrl + '?username=' + username + '&password=' + password)
.toPromise()
.then(response => response.json())
.catch(function(e){
this.handler(e);
})
}
handler (e: Response){
throw e;
}
我错过了什么吗?
谢谢。
编辑
我按照建议使用了arrow function,现在我的代码如下所示:
user.service.ts
login(username: string, password: string): Promise<User> {
return this.http
.get(this.loginUrl + '?username=' + username + '&password=' + password)
.toPromise()
.then(response => response.json())
.catch(e => {
this.handler;
})
}
handler (e: Response){
throw e;
}
login.component.ts
onSubmit(loginForm: NgForm): string {
this.userService.login(loginForm.value.username, loginForm.value.password)
.then(data => {
this.message = 'Nome: ' + data.nome +
' Cognome: ' +data.cognome +
' Azienda: ' + data.azienda +
' Ufficio: ' + data.ufficio;
})
.catch(e => {
this.message = e;
});
return this.message;
}
尽管如此,我还是从服务器获得了异常,但应用程序跳过了 catch() 块。
【问题讨论】:
-
控制台中的异常是什么?
-
你又在处理程序中抛出异常?此外,如果您想使用
this,您应该使用arrow function 而不是匿名函数 -
@Maximus 是
401 Unauthorized,但我认为这不是问题。 -
@0mpurdy 我是,但箭头函数是关键点。我将编辑我的代码以进一步参考该解决方案。如果您将您的评论作为答案,我会选择它作为正确的。谢谢。
-
@esseara 看起来已经有这个效果的答案,可以接受:) 另外,我不确定,但最好不要在你的问题中包含答案- 它可能会混淆未来的访问者:)
标签: javascript angular typescript exception promise