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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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...
You might want to take a look at this example with interceptors: stackoverflow.com/questions/11956827/…
@m.e.conroy That link made it crystal clear, thanks! Interceptors turned out to be not so hard after all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.