Search code examples
phpjquerymysqljsonmysql-error-1146

Catching errors from server side


I am getting json data from my server to show them as a table.

$('#queryFrom').ajaxForm({                    
                dataType:  'json',                                        
                beforeSubmit:  showRequest,  // pre-submit callback
                success:   processJson,                    
                error: function (xhr, ajaxOptions, thrownError){
                    $('#queryResult').html('<div class="ui-corner-all ui-state-error"><p><span class="ui-icon ui-icon-alert"></span>'+thrownError+'</p></div>');
                    $('#queryResult').show("slow");
                }
            });

Can I somehow separate the mysql errors from json/ajax erros side? Currently I am getting :Invalid JSON: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'simover.simulation' doesn't exist{} Can I customise the messages thrown by jquery? thanks Arman.

EDIT

one can use xhr.responceTxt instead of thrownError.


Solution

  • Currently your error callback is getting called because you have an error in your server response, not because your server encountered a problem. Javascript engine throws an error because it expects JSON data to be sent back, but instead it gets a plain string Base table or view not found..., which is not a valid JSON string.

    I would suggest that you catch those errors on the server for example by using try and catch blocks and sending back some kind of special response in case an error occurs. Like this:

    {
        "ok": false, 
        "error_key": "database_error", 
        "error_text": "Base table or view not found: 1146 Table 'simover.simulation' doesn't exist"
    }