Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean way to throw php exception through jquery/ajax and json

Tags:

jquery

php

Is there a clean, easy way to throw php exceptions through a json response jquery/ajax call.

like image 822
madphp Avatar asked Oct 02 '12 15:10

madphp


2 Answers

You could do something like this in PHP (assuming this gets called via AJAX):

<?php  try {     if (some_bad_condition) {         throw new Exception('Test error', 123);     }     echo json_encode(array(         'result' => 'vanilla!',     )); } catch (Exception $e) {     echo json_encode(array(         'error' => array(             'msg' => $e->getMessage(),             'code' => $e->getCode(),         ),     )); } 

In JavaScript:

$.ajax({     // ...     success: function(data) {         if (data.error) {             // handle the error             throw data.error.msg;         }         alert(data.result);     } }); 

You can also trigger the error: handler of $.ajax() by returning a 400 (for example) header:

header('HTTP/1.0 400 Bad error'); 

Or use Status: if you're on FastCGI. Note that the error: handler doesn't receive the error details; to accomplish that you have to override how $.ajax() works :)

like image 193
Ja͢ck Avatar answered Oct 14 '22 19:10

Ja͢ck


Facebook do something in their PHP SDK where they throw an exception if a HTTP request failed for whatever reason. You could take this approach, and just return the error and exception details if an exception is thrown:

<?php  header('Content-Type: application/json');  try {     // something; result successful     echo json_encode(array(         'results' => $results     )); } catch (Exception $e) {     echo json_encode(array(         'error' => array(             'code' => $e->getCode(),             'message' => $e->getMessage()         )     )); } 

You can then just listen for the error key in your AJAX calls in JavaScript:

<script>     $.getJSON('http://example.com/some_endpoint.php', function(response) {         if (response.error) {             // an error occurred         }         else {             $.each(response.results, function(i, result) {                 // do something with each result             });         }     }); </script> 
like image 32
Martin Bean Avatar answered Oct 14 '22 19:10

Martin Bean