0

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);
    }
1
  • 1
    $http methods return a $q promise so just use a promise catch() Commented Mar 29, 2021 at 22:51

1 Answer 1

0

You could do the following:

set_error_handler("warning_handler", E_WARNING);
/// Run your code that throws the warning
// Wherever this is running Reminder::save($json);
restore_error_handler();

function warning_handler($errno, $errstr) { 
    // do something like log to a real place?
}
Sign up to request clarification or add additional context in comments.

Comments

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.