我无法处理json解码错误.我在下面提到我的代码: -
try{
$jsonData=file_get_contents($filePath). ']';
$jsonObj = json_decode($jsonData, true);
} catch(Exception $e){
echo '{"result":"FALSE","message":"Caught exception: '.
$e->getMessage().' ~'.$filePath.'"}';
}
Run Code Online (Sandbox Code Playgroud)
我是新的php程序员.对不起,如果出了什么问题.
我最近遇到了一些代码,它使用自定义错误处理程序将任何PHP错误转换为通用应用程序异常.还定义了一个自定义异常处理程序,如果异常位于特定的错误代码范围内,它将记录该异常.例:
class AppException extends Exception
{
}
function error_handler($errno, $errstr, $errfile, $errline)
{
throw new AppException($errstr, $errno);
}
function exception_handler($exception)
{
$min = ...;
$max = ...;
if ($exception->getCode() >= $min && $exception->getCode() <= $max)
{
// log exception
}
}
set_error_handler('error_handler');
set_exception_handler('exception_handler');
$a[1]; // throws exception
Run Code Online (Sandbox Code Playgroud)
问题是我看到了以下内容:
try
{
do_something();
}
catch (AppException $exception)
{
}
Run Code Online (Sandbox Code Playgroud)
这意味着实际编程错误与"异常"行为之间没有区别.在进一步挖掘之后,我发现了围绕PHP错误代表"异常"行为的想法设计的部分代码,例如:
...
function my_function($param1, $param2)
{
// do something great
}
try
{
my_function('only_one_param');
}
catch (AppException $exception)
{
}
Run Code Online (Sandbox Code Playgroud)
这最终会混淆错误和应用程序界面的设计.
您对这种处理错误有何看法?是否值得将PHP的原生错误转化为异常?在上述代码库是围绕这个想法设计的情况下你做了什么?