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:\depot\web\qms2\qms\php-api\crm.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 $http.post(API_URL + '/login', xsrf, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
}
catch (e) {
console.log("HTTP error: ", e);
}
$httpmethods return a $q promise so just use a promise catch()