简体   繁体   中英

Best way to handle PHP runtime errors/notices/warnings with JQuery

I know the title of the question is not very objective, but it is kind of difficult to explain my situation. Thing is, I want to create a way in which I can handle all possible errors with my $.post calls so I can give the correct message to the user, given the situation.

I have some functions returning JSON objects as a result. If an error is thrown within my application, a status code 500 is generated thus making it easy for me to catch and handle this error. But if a runtime error occurs (say, trying to execute a method on a null object) then PHP does not raise a 500 error, it only displays an error message, gives a 200 status and carries the execution. I try to simulate this error to see how best to handle it, but I'm out of ideas.

I have this code:

$(function() {
$('#update_marker').submit(function(e) {
    e.preventDefault();
    $.post($("#update_marker").attr("action"), $("#update_marker").serialize(), function(data, textStatus, jqXHR) {
        var json = $.parseJSON( data );
        if( json.status=="success" ) {
            new Messi( json.msg );
        } else {
            new Messi( json.msg, {title: 'Ops..', titleClass: 'anim error', buttons: [{id: 0, label: 'Fechar', val: 'X'}]});
        }
    }).fail( function(jqXHR, textStatus, errorThrown) { general_error(); } );
    return false;
});
});

So in my called method, I put some code like $nullobj->method(); just to simulate an unexpected failure. And what I get is the result below, with a status code=200 (OK).

<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">

<h4>A PHP Error was encountered</h4>

<p>Severity: Notice</p>
<p>Message:  Undefined variable: nullobj</p>
<p>Filename: controllers/map.php</p>
<p>Line Number: 140</p>

</div><br />
<b>Fatal error</b>:  Call to a member function method() on a non-object in <b>D:\xampp\htdocs\xumb\application\controllers\map.php</b> on line <b>140</b><br />

This will result in my jQuery code treating this a Success and failing to parse the JSON object, thus not showing anything to the user. In some cases, the execution will not even stop at the error, and the JSON returned will be there, but at the bottom of the page, unaccessible. I could check the returned object to see if it's JSON, but it's a little more than that - I think.

You can make your own PHP error handler. Then you can return status 500 on certain or any error. See this post: How can I get php to return 500 upon encountering a fatal exception?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM