Author Topic: Correct way to throw exceptions in PRO?  (Read 2914 times)

dbadmin

  • Pro Economy
  • Jr. Member
  • *
  • Posts: 67
    • View Profile
Correct way to throw exceptions in PRO?
« on: June 17, 2014, 07:32:31 pm »
Hi,

Could you share what is the correct way to throw exceptions from PHP server side so that it gets caught in "error" section of ajax call?
If I just throw new Exception, the call goes to "getData" and doesn't go to "error".


   var dataModel = {
           location: "remote",
           sorting: "local",
           pageModel: { type: "remote", rPP: 20, strRpp: "{0}", curPage: 1 },         
           dataType: "JSON",
           method: "POST",
           recIndx: "PlantID",
           getUrl: function (ui)
              {
                 var dataModel = ui.dataModel.pageModel;
                 var filters = { "name" : $("#txName").val(),
                             "curPage": dataModel.curPage,
                             "recPerPage": dataModel.rPP,
                                 };
                   return {
                    url: "../services/Search.php",
                     data: { dataBuffer: filters }
                };
            },
           getData: function (dataJSON)  // on error ends up here and dataJSON is NULL
           {
               var data = dataJSON.DataArray;               
               return { curPage: dataJSON.curPage, totalRecords:1000, data: data };
           },
           error: function (err) // does not end up here
           {
              alert ("Error: " + err + "\n Please contact administrator with your input!");
          }           
       };


Thanks!

paramvir

  • Administrator
  • Hero Member
  • *****
  • Posts: 6263
    • View Profile
Re: Correct way to throw exceptions in PRO?
« Reply #1 on: June 19, 2014, 12:42:16 am »
uncaught errors in PHP script leads to invalid JSON response from server and / or 500 (internal server error ) which in order leads to execution of error callback by jQuery.

Code: [Select]
        error: function(jqXHR, textStatus, errorThrown){
            alert(textStatus);
        },

error is useful for troubleshooting by developers.

If you are looking to display more meaningful error messages from PHP to users, then use try catch similar to this:
Code: [Select]
    try{

             code here.....
    }
    catch(Exception $ex){
        $error = array("error" => $ex->getMessage());
        //print_r($error);
        echo json_encode($error);
        exit;
    }

and in dataModel.getData
Code: [Select]
        getData: function (response) {
            if(response.error){
                alert(response.error);
                return {data: []};
            }
            else{
                return { data: response.data };
            }
        }