Catch angular.js HTTP response JSON parse errors?

  angularjs, php

I have a legacy angular.js app that uses a PHP backend. If there is a bug in the PHP code, angular.js spews an unhelpful error like this:

angular.js:14199 SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at fromJson (angular.js:1345)
    at defaultHttpResponseTransform (angular.js:10878)
    at angular.js:10969
    at forEach (angular.js:325)
    at transformData (angular.js:10968)
    at transformResponse (angular.js:11828)
    at processQueue (angular.js:16696)
    at angular.js:16712
    at Scope.$eval (angular.js:17994)

If I look in the Developer Console > Network > Response, I can find that the problem is that the PHP backend is just echoing HTML instead of a JSON, i.e. something like:

<br />
<b>Warning</b>:  Declaration of Reminder::save($json) should be compatible with CRMTable::save($json, $customFilter = NULL, $addLogEntry = true) in <b>C:depotwebqms2qmsphp-apicrm.php</b> on line <b>710</b><br />
<br />

Is there a way to ‘catch’ these parse errors so I can handle them better? Wrapping the HTTP POST call with try/catch doesn’t help:

    try {
        return $ + '/login', xsrf, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
    catch (e) {
        console.log("HTTP error:  ", e);

Source: AngularJS Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.