Javascript 如何从回调函数捕获错误
我有一个与此相关的组件: this.loginService.login.user,=>{ 这个.router.navigateByUrl'/';Javascript 如何从回调函数捕获错误,javascript,typescript,Javascript,Typescript,我有一个与此相关的组件: this.loginService.login.user,=>{ 这个.router.navigateByUrl'/'; }; 您可以将函数调用包围在try/catch块中 try { this.loginService.login(this.user, () => { this.router.navigateByUrl('/'); }); } catch (error) { // do something with th
}; 您可以将函数调用包围在try/catch块中
try {
this.loginService.login(this.user, () => {
this.router.navigateByUrl('/');
});
} catch (error) {
// do something with the thrown error
}
将错误作为回调函数的第一个参数传递是一种常见的模式。因此,您的登录功能将如下所示: logincredentials,回调{ this.http.getoptions.subscriberResponse=>{ //逻辑(假设成功)调用回调,第一个参数为null callbacknull },错误=>{ //如果发生错误,请将错误异常作为第一个参数传递 回拨错误 }; } 因此,您可以在组件中处理此问题:
login(credentials, successCallback, errorCallback) {
const headers = new HttpHeaders(credentials ? {
authorization: 'Basic ' + btoa(credentials.email + ':' + credentials.password)
} :
{});
this.http.get(this.API.crudAdmin + 'admin?email=' + credentials.email, {
headers: headers
}).subscribe(response => {
if (response['name']) {
this.authenticated = true;
} else {
this.authenticated = false;
}
successCallback && successCallback();
},
errorCallback);
}
this.loginService.logincredentials,错误=>{
如果错误{
//显示错误对话框等
}否则{
这个.router.navigateByUrl'/';
}
}
您可以在传递成功回调的同时传递错误回调函数。GET请求失败时将调用错误回调:
this.loginService.login(this.user,
() => this.router.navigateByUrl('/'),
//handle the error here, log to an error service etc.
(err) = > console.error(err)
);
在服务端,在Observable的错误处理程序中,调用从组件传递的errorCallback:
login(credentials, successCallback, errorCallback) {
const headers = new HttpHeaders(credentials ? {
authorization: 'Basic ' + btoa(credentials.email + ':' + credentials.password)
} :
{});
this.http.get(this.API.crudAdmin + 'admin?email=' + credentials.email, {
headers: headers
}).subscribe(response => {
if (response['name']) {
this.authenticated = true;
} else {
this.authenticated = false;
}
successCallback && successCallback();
},
errorCallback);
}
传统的try-catch在这里不起作用,因为这是一个异步操作,当GET最终失败时,catch块将无法捕获错误
这是因为loginService.login方法在后台异步发出GET请求时立即返回。GET中的任何错误都不会被loginService.login调用周围的catch块处理。如果错误是从回调内部抛出的,例如navigateByURL抛出的,则不会有帮助。这是真的。我没有看到他在标题中提到回调,而只是登录方法在问题正文中抛出的错误。不管怎样,这个问题看起来已经得到了回答,所以我将保持原样。