【发布时间】:2017-07-24 23:33:23
【问题描述】:
我有一个 php 脚本,它从数据库中读取记录并返回一个 json 对象。我在脚本中有错误处理,因此如果抛出异常或发生其他错误,我仍然返回格式正确的 json 响应(带有错误代码和所有内容)。这行得通。
但是:如果 PHP 觉得它有话要说,它在发送 json 响应后仍然会说。这会破坏客户端的 json 解析器。因此,不是 ajax 调用成功并显示诸如“找不到数据库文件”之类的错误消息,而是调用失败并出现 json 解析器错误,这没有帮助(因为它覆盖了原始的、保留的错误信息):
SyntaxError: JSON.parse: unexpected non-whitespace character
after JSON data at line 1 column 120 of the JSON data
我可以使用 error_reporting(0) 抑制 PHP 的消息 - 但有更好的方法吗?代码(大纲)如下:
<?php
header('Content-type: application/json');
const RESP_OK = 0;
const RESP_EXCEPTION = 1;
try {
// do the database stuff and build $response
$response['exitcode'] = RESP_OK;
} catch ( Exception $e ) {
// put error info in the response
$response['exitcode'] = RESP_EXCEPTION;
$response['error'] = 'code: ' . $e->getCode() . ' (line ' .
$e->getLine() . ') message: ' . $e->getMessage();
} finally {
// always send back a response
echo json_encode( $response );
error_reporting(0);
// also close the db here etc.
}
?>
【问题讨论】:
-
我会附和 Maarten 的回答 - 防止 PHP 错误和警告的最佳方法是追踪导致它们的原因,而不是寻找绕过它们的方法。
-
我同意。关键是,我已经在检查(所有)错误。这就像异常:一旦你使用 try/catch 来处理它们,你不希望发生默认的异常行为(例如,你希望你自己的错误消息在你自己的应用程序中正确显示)。我可以捕获异常,但没有 try/catch 用于 php 警告和通知(有吗?),所以即使我检查了所有结果并相应地继续,php 仍然会发出它们并破坏应用程序。
-
返回的 JSON 数据是什么?那么我们来看看是什么产生了这个意想不到的空白字符呢? :)
标签: php json ajax error-handling