[英]Error handling in angular using try catch with pipe and map
How can I return an error and send it to the component ts so that the users can detect whats the error?如何返回错误并将其发送到组件 ts 以便用户可以检测到错误是什么? Codes below is a login function.下面的代码是登录 function。
I want an error message coming from the API to return at component ts and display it as angular material toast.我希望来自 API 的错误消息在组件 ts 处返回并将其显示为 angular 材料吐司。
signIn(payload: signInRequestPayload): Observable<Account> {
try {
return this.query({
document: login_user
payload,
}).pipe(
map((result: any) => {
console.log(result);
if (result.data.length) {
return result.data[0] as Account;
}
throw Error("")
})
);
} catch (error) {
throw Error(`Unable to retrieve user account`);
}
} }
We can throw an error inside of the map
and the subscriber
can handle the error.我们可以在map
内部抛出一个错误, subscriber
可以处理该错误。
signIn(payload: signInRequestPayload): Observable<Account> {
return this.query({
document: login_user,
payload,
}).pipe(
map((result: any) => {
if (result.data.length) {
return result.data[0] as Account;
} else {
throw new Error('...');
}
});
);
}
Then it should be up to the subscriber to handle the error:然后应该由订阅者来处理错误:
The first callback function is for success and the second callback is for the error scenario.第一个回调 function 用于成功,第二个回调用于错误场景。
signIn.subscribe(response => {/* successful response */}, error => {/* error response */});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.