what is the difference between error handler and interceptor in angular 2?

你离开我真会死。 提交于 2019-12-22 08:52:01

问题


And also what would be the best solution for front end error handling in ng2 for real-time web app?

Is it fine to use 'Http interceptor' for front end error handling? Please explain about these things.


回答1:


What is the difference between error handler and interceptor in angular 2?:

Based on the Angular documentation, this is how they are defined:

ErrorHandler: The default implementation of ErrorHandler prints error messages to the console.


HttpInterceptor: Typically an interceptor will transform the outgoing request before returning next.handle(transformedReq). An interceptor may choose to transform the response event stream as well, by applying additional Rx operators on the stream returned by next.handle().

More rarely, an interceptor may choose to completely handle the request itself, and compose a new event stream instead of invoking next.handle(). This is acceptable behavior, but keep in mind further interceptors will be skipped entirely.

It is also rare but valid for an interceptor to return multiple responses on the event stream for a single request.

This leads me to believe that the sole purpose of ErrorHandler is to determine how the error will be persisted in order for the developer to realize that an error has occurred in the application. The default behavior is to persist the error in the console where a developer can easily determine if errors are being thrown by the app. A simple use case would be if you wanted to log the errors in some type of persistent storage so that a developer can comb through the logs for any client side errors.

Now, an HttpInterceptor is used when you want to manipulate a request before it's sent to the server. A simple use case would be if you wanted to add a header to all request, manipulate the body, lower-case the request URL, etc.

What would be the best solution for front end error handling in ng2 for real-time web app?:

If you just want to log any error in your angular app, write your own custom ErrorHandler to Intercept error handling. Inside your custom error handler use a service to log the error to persistent storage.

Is it fine to use 'Http interceptor' for front end error handling? It all depends on your use case. Say you want to notify the client via a SnackBar when a 500 occurs, you can write an interceptor that catches the request, inspects the response for a 500, then shows a red SnackBar and rethrows the error so that the service that made the call can do some additional error handling.

Hope this helps :)



来源:https://stackoverflow.com/questions/48191831/what-is-the-difference-between-error-handler-and-interceptor-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!