本文介绍了发生错误时,您可以告诉PHP发送标题(如500)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我目前的项目中,我正在使用正常的HTTP请求来查询PHP,而且还通过AJAX,我有时会返回JSON格式的数据,有时候会返回正常的文本。当发生错误时,在正常请求中,您会看到错误消息,并可以做一些事情。另一方面,使用AJAX请求,您无法确定是否收到错误或数据,因为它不会直接显示 - 您只是遇到麻烦,因为您的应用程序将不再工作。



所以我想到了一个错误处理系统。我最好的想法是发送一个500的内部服务器错误头,如果发生错误,所以在我的JS中,当我发送一个AJAX请求,我可以简单地检查错误的方式和处理它。



不幸的是,PHP不会发送这种标题(比如当你有一个解析错误,或者你的代码中的某些东西出错)。



你可以



a)如果发生错误,请告诉PHP发送头像500?或
b)使用set_error_handler发送一个500标题,然后调用PHP常规错误处理?或
c)当您发生PHP错误时,您能否以其他方式发出错误标题?



谢谢
Lukas

解决方案

我更喜欢使用异常来处理错误。首先,您需要安装错误到异常错误处理程序(http://php.net/manual/en/class.errorexception.php,示例1),然后将主应用程序代码包装在try-catch块中并发送捕捉部分中的相应标题。例如:

  try {
$ myApplication-> run();
} catch(异常$ e){
//记录或以其他方式注册错误
header('HTTP / 1.1 500 Internal Server Error');
}

不幸的是,这并不适用于所谓的致命错误要处理这些,你必须使用这样的愚蠢技巧

  ob_start(); 

register_shutdown_function(function(){
$ p = ob_get_contents();
if(preg_match('〜致命错误〜',$ p))
header 'HTTP / 1.0 500 Internal Server Error');
});

...您的代码...


in my current Project I'm querying PHP with normal HTTP-request but also via AJAX where I sometimes return JSON-formatted data and sometimes normal text. When an error occurs, in a normal request, you see the error-message and can do something about it. With AJAX-requests on the other hand you cannot be sure if you get an error or the data you want because it isn't displayed directly — you just run into troubles because your app won't work anymore.

So I thought about an error-handling-system. My best idea is to send a 500 "Internal Server Error" header if an error occurs, so in my JS, when I send an AJAX-Request, I can simply check for errors that way and handle it.

Unfortunately PHP doesn't send that kind of header (like when you have a parse-error, or something in your code goes wrong) natively.

Can you

a) Tell PHP to send headers like 500 if an error occurs? Orb) Use set_error_handler to send a 500-header and then call PHP regular errorhandling? Orc) Can you, in any other way sen error-headers when a PHP error occurs?

Thanks,Lukas

解决方案

i prefer using Exceptions for handling errors. First, you need to install error-to-exception error handler (http://php.net/manual/en/class.errorexception.php, example 1), then wrap your main application code in a try-catch block and send appropriate headers in the catch part. For example:

try {
    $myApplication->run();
} catch(Exception $e) {
   // log or otherwise register the error
   header('HTTP/1.1 500 Internal Server Error');
}

unfortunately, this doesn't work with so-called "Fatal errors", to handle these you have to use stupid tricks like this

ob_start();

register_shutdown_function(function() {
    $p = ob_get_contents();
    if(preg_match('~Fatal error~', $p))
        header('HTTP/1.0 500 Internal Server Error');
});

...your code... 

这篇关于发生错误时,您可以告诉PHP发送标题(如500)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 17:54