我想知道如何正确处理和控制Angular&Web API中的错误,
在一些教程中,我看到错误是在组件中处理的,而不是在获取数据的服务中处理的..基本上,后端和Angular/clients错误都在这样的组件中处理:
我想知道他如何处理组件中的后端和前端错误?那是否意味着我不需要在Web API中尝试/捕获?这还应该处理吗?
我在这里很困惑,请向我解释这个例子...
而且我认为错误处理程序应该添加到service.ts
中-在此示例PeopleService
中,而PeopleService
看起来像这样:
所以我对此感到困惑:
Shouldn't there be logic in a service.ts which would handle errors?
Shouldn't I wrote try/catch in a WebApi, how come backend errors are handled here?
谢谢你们的帮助
干杯!
最佳答案
在您的示例中,后端错误类似于服务器响应404(未找到)的情况。例如,您通过id请求一个特定的人,而服务器未找到与该id相关的任何人,因此它返回404响应。这样,客户端将知道用户要查找的人不存在。
Shouldn't there be logic in a service.ts which would handle errors?
从Angular guide:
Error inspection, interpretation, and resolution is something you want to do in the service, not in the component.
错误封装在服务而不是组件的
ErrorObservable
中。然后在您的组件中,您将执行以下操作:
service.subscribe(
result => this.result = result,
error => console.log(error)
);
Shouldn't I wrote try/catch in a WebApi, how come backend errors are handled here?
您不处理后端发生的错误。您正在处理从服务器响应返回的错误。例如:如果后端处理中存在空引用错误,则该错误不会像您的示例那样使您的服务器崩溃。
后端是其自身的过程。它有自己的错误处理程序。客户端代码( Angular )在用户的浏览器中运行。
您可以在angular site上查看该指南以获取更多信息。
关于angular - 如何正确处理和控制Angular和Web API中的错误-2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50098211/