Angular: Default handler for unhandled http errors-Collection of common programming errors
In my angularjs app, I defined a default handler for http errors this way:
myapp.config([ '$httpProvider', function($httpProvider) {
$httpProvider.responseInterceptors.push('errorInterceptor')
}])
where errorInterceptor
is a service that displays some details about the error in an alert field on the top of the current page.
Now, when I want to handle a specific error in a different way (say the query is triggered in a modal, and I want to display the alert only in this modal, and not at page level):
$http.get('/my/request').then(success, specificErrorHandling)
Angular does the specificErrorHandling
but still triggers my errorInterceptor
, so my error gets reported twice. Is there a way to avoid that?
More generically, is there an Angular way to handle only errors that aren’t already taken care of along the promise
chain, the same way the top-level error handler of a server app doesn’t have to handle catched exceptions?
Edit: As requested by Beetroot-Beetroot in comments, here is the code for my interceptor:
@app.factory 'errorInterceptor', [ '$q', 'alertsHandler',
($q, alertsHandler) ->
success = (response) ->
response
failure = (response) ->
alertsHandler.raise(response)
(promise) ->
promise.then success, failure
]
-
Assuming that you know which errors needs to be suppressed and which one need to be propagate. Also since the Response interceptor is a function that returns promise itself
You can catch the response for failure case and instead of propagating it up the stack you can return something such as empty response.
If you look at the sample example in angular documentation for interceptor
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { return function(promise) { return promise.then(function(response) { // do something on success }, function(response) { // do something on error if (canRecover(response)) { return responseOrNewPromise; // This can suppress the error. } return $q.reject(response); // This propogates it. }); } });
Originally posted 2013-12-02 01:21:13.