开发者

Custom PHP Errors for AJAX calls

I'm building a web application, and am wondering how to handle errors with my AJAX calls. For instance, if the user enters some sort of data that is invalid (bad email address, user already exists) I want to be able to throw an error from PHP.

I've seen here http://php4every1.com/tutorials/jquery-ajax-tutorial/ that you could just use a JSON object and handle the error report from JQuery's Success function, but that doesn't seem like the right way to do 开发者_运维技巧it. It would make sense to me that jQuery's error function should be utilized when there is an error. I guess I'm a stickler for that kind of thing.

Here's how I'm doing it right now.

//In my PHP file called from JQuery
function error($msg) {
    header("HTTP/1.0 555 ".$msg);
    die();
}
//Then that error is handled accordingly from JQuery

So I'm creating an error code of 555—which is not defined as anything—and tacking on my own custom error message. Is that the right way to do this? Should I just use JSON? There's gotta be a standard way to send out error messages like this, right?

If you need to see more of my code to get a better idea, the whole project is up on github: https://github.com/josephwegner/fileDrop. The file in question is config/phpFuncts.php.


I'd just use a JSON object and an HTTP header of 200. There was nothing wrong with the request itself, and your server behaved as it was supposed to - the error was on a different layer of the abstraction.


The 400 family of HTTP status codes indicate that there was a problem with the request. I would set the response code to 400 and include the list of error messages in the response body as JSON.


I hate using HTTP status codes for indicating failures. The HTTP codes should be reserved for actual HTTP-level errors, and errors related to the AJAX request should be sent back via a JSON structure.

e.g.

$data = array()
if (some big ugly computation fails) {
   $data['errorcode'] = -123;
   $data['error'] = true;
   $data['success'] = false;
   $data['errormessage'] = 'some helpful error message';
} else {
   $data['success'] = true;
   $data['error'] = false;
   $data['response'] = 'whatever you wanted to send back....';
}
echo json_encode($data);

Then on the client-side

if (data.error) {
   alert('Request blew up: ' + data.errormessage);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜