0

I am using $resource in Angular js. I want to configure $resource using $resourceProvider in such a way that I can handle the server response.

For Example

I am doing a get request for user profile and if I get 500 error from server I should give an alert("Something went wrong at server"); and if I get 403 I should give alert("You don't have permission to access this resource"); How can I achieve this?

I have done some other configuration like this:

$resourceProvider.defaults.actions.update = {
   method: 'PUT'
};

This works fine the same way I want to achieve this goal.

Thanks.

Arpit Kumar
  • 2,179
  • 5
  • 28
  • 53
  • The `$resource` should not pop up alerts, that's a mixing of responsibilities that makes it a headache to reuse. A *controller* should be responsible for popping up visible alerts and such, not a backend service. – deceze Mar 16 '17 at 08:50
  • @_deceze_ Thanks, I very much agree with you. But I want a mechanism through which I can inform my service to show an `alert()` – Arpit Kumar Mar 16 '17 at 08:52
  • Have a look at [the angular http docs](https://docs.angularjs.org/api/ng/service/$http) – g_uint Mar 16 '17 at 08:52
  • Instead of `resourceProvider` consider to use `$httpProvider` - like that http://stackoverflow.com/questions/25041929/angularjs-routeprovider-http-status-403/25043231#25043231 – Krzysztof Safjanowski Mar 16 '17 at 08:54

1 Answers1

0

You should create a responseError interceptor to handle any type of error.

Here is plunker to demonstrate the use of interceptor.

https://plnkr.co/edit/4E2YAiwCOgA1Nw5d7CC2?p=preview

This will not give any error.

Go to resource.js file and change this line

restPath = 'https://www.googleapis.com/books/v1/volumes'

to restPath = 'https://www.googleapis.com/books/v1/volumes1212'

Now you will see an alert message for 404

Mohan Singh
  • 883
  • 8
  • 18