2

As can be seen in AngularJS's source, any $http.post request that returns an HTTP code in the 200-299 range will trigger the success() callback even if the response contains invalid data (like for example invalid JSON).

I'm specifically setting my call's responseType: 'json' and even then the success callback is fired when something else comes back. This is especially annoying in the development server where PHP's display_errors setting is turned on. When something goes wrong server-side and PHP outputs an error message the AngularJS app doesn't detect this and continues happily.

Is there a way to prevent this? I mean, to make the AngularJS app fire the error() callback when the response data is invalid JSON?

Thanks

Julian
  • 8,808
  • 8
  • 51
  • 90

1 Answers1

2

so your PHP server responds with a 200 error code even on an error? Not knowing PHP, this feels like a server configuration problem to me. I'd expect a 500 error with a payload. That being said, there are two things that I can think of offhand.

$http includes transformResponse handlers you can set up to inspect the response for problems.

$http also includes the concept of "interceptors" which allow you to pick up the response payload and do something with it. You could use an interceptor to "reject" the response.

More information on transformResponse and "interceptors" in the $http documentation: http://docs.angularjs.org/api/ng.$http

Brian Genisio
  • 47,787
  • 16
  • 124
  • 167
  • 1
    Thanks for the info. I just tried transforming the response but soon realized that I can't do anything once I detect that the JSON is invalid because the code path still goes through the success() callback. So I might need to use the interceptors as they seem to have the ability to reject the whole thing. The only problem is that they look like black magic to me (still learning AngularJS) so I will need to do some reading first. It's a shame that the Angular docs are not n00b oriented... – Julian Aug 31 '13 at 22:23
  • 2
    You might want to take a look at this example with interceptors: http://stackoverflow.com/questions/11956827/angularjs-intercept-all-http-json-responses?rq=1 – m.e.conroy Aug 31 '13 at 23:49
  • 1
    @m.e.conroy That link made it crystal clear, thanks! Interceptors turned out to be not so hard after all. – Julian Sep 01 '13 at 07:31