以符合常规内容的JSON格式报告PHP错误类型
我使用AngularJs作为单页应用程序,并通过JSON与服务器端PHP进行通信。 PHP的首部设置了JSON,但错误从PHP报告:以符合常规内容的JSON格式报告PHP错误类型
php_flag display_errors 1
php_flag display_startup_errors 1
php_value error_reporting 32767
是HTML和不匹配的常规答案header('Content-Type: application/json;charset=utf-8');
因此不断angularjs的Content-Type头的PHP错误抛出。我应该使用multicontent types还是该怎么办?
如果您必须将PHP错误/异常返回给客户端,这是不推荐的(但我知道,开发起来更容易),您需要PHP的自定义error/uncaught- exception处理程序。通过这种方式,您可以自定义错误/例外的显示方式。
下面是一个示例代码,将错误和未捕获的异常输出为JSON对象。
// Set error handler
set_error_handler('api_error_handler');
function api_error_handler($errno, $errstr) {
return api_error($errstr, $errno, 500);
}
// Set uncaught exceptions handler
set_exception_handler('api_exception_handler');
function api_exception_handler($exception) {
return api_error($exception->getMessage(), $exception->getCode(), 500);
}
// Error/Exception helper
function api_error($error, $errno, $code) {
// In production, you might want to suppress all these verbose errors
// and throw a generic `500 Internal Error` error for all kinds of
// errors and exceptions.
if ($environment == 'production') {
$errno = 500;
$error = 'Internal Server Error!';
}
http_response_code($code);
header('Content-Type: application/json');
return json_encode([
'success' => false,
'errno' => $errno,
'error' => $error,
]);
}
但是这还不是全部;由于用户定义的错误处理程序无法处理致命错误,因此仍会显示致命错误消息。你需要与ini_set()
调用禁用显示错误信息:
ini_set('display_errors', 0);
那么如何处理的致命错误?致命错误可以使用register_shutdown_function()
在关机时处理。在关机处理程序中,我们需要通过调用error_get_last()
来获取最新的错误信息。所以:
// Set shutdown handler
register_shutdown_function('api_fatal_error_handler');
function api_fatal_error_handler() {
$error = error_get_last();
if ($error && error_reporting() && $error['type'] === E_ERROR) {
return api_error($error['message'], E_CORE_ERROR, 500);
}
}
然后在javascript的东西方面,你必须添加一个错误回调并向用户显示错误信息。
毕竟,为什么不使用成熟的错误/异常处理程序包而不是实现所有这些?满足Whoops。
你为什么要依靠PHP错误您的应用? 如果可能,请提供引发错误的代码部分。
您不应该使用PHP错误来停止您的应用程序,而是如果您需要返回JSON结果,请执行干净退出。 您可以使用try...catch
模式或在实际调用之前检查引发错误的语句(例如,检查是否可以继续执行)。
看一看这里:
- Clean way to throw php exception through jquery/ajax and json
- How handling error of json decode by try and catch
一定要记住关闭错误在最终应用程序:他们可能泄漏了大量的信息,攻击者(和此外,他们看起来很糟糕)。
代码很好,只是方便查看解析的json中的php错误,以便在角度表达式中直接查看任何错误。与信息泄漏良好的提示。 – ItsmeJulian