Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PHP最佳实践之异常和错误 #11

Open
xx19941215 opened this issue Jul 25, 2017 · 0 comments
Open

PHP最佳实践之异常和错误 #11

xx19941215 opened this issue Jul 25, 2017 · 0 comments

Comments

@xx19941215
Copy link
Owner

异常

1).异常是Exception类的对象,在遇到无法修复的状况时抛出,例如远程API没有响应或者数据库查询失败再或者是无法满足程序运行的前置条件。出现问题的时候异常用于主动出击,委托职责;异常还可以用于防守,预测潜在的问题来减轻影响。
2).Exception对象和其他的PHP对象一样,使用new关键字实例化。

<?php
$exception = new Exception('userId cannot be null', 100);

第一个参数是消息,第二个参数是数字代码。数字代码是可选的,用于为指定的异常提供上下文。我们可以使用公开的实例方法getCodegetMessage来获得异常对象的两个属性。
3).假如遇到了异常情况,或者在当前的条件下无法操作,我们需要抛出异常。

<?php
throw new Exception('Something went wrong.Time for lunch!');

4).我们必须抛出Exception类或者他的子类,PHP内置的异常类和其子类如下:

  • Exception
  • ErrorException
    PHP标准库提供了下述额外的Exception子类,扩展了PHP内置的异常类。
  • LogicException
  • BadFunctionCallException
    • BadMethodCallException
  • DomainException
  • InvalidArgumentException
  • LengthException
  • OutOfBoundsException
  • RuntimeException
  • OutOfBoundsException
  • OverflowException
  • RangeException
  • UnderflowException
  • UnexpectedValueException

5).捕获异常。预测和捕获并处理异常是我们自己的责任,因为未捕获的异常可能会导致PHP应用终止运行,显示错误信息。拦截并处理潜在异常的方式是,把可能抛出异常的代码放在在try/catch块中。

try {
    $pdo = new PDO('mysql://host=wrong_host;dbname=wrong_name');
} catch (PDOException $e) {
    $code = $e->getCode();
    $message = $e->getMessage();
    echo 'Something went wrong.Check back soon, please';
    exit;
}

还可以连续抛出多个异常

try {
  throw new Exception('Not a PDO exception');
  $pdo = new PDO('mysql://host=wrong_host;dbname=wrong_name');
} catch (PDOException $e) {
    echo 'Caught PDO exception';
} catch (Exception $e) {
    //处理其他异常
    echo 'Caught generic exception';
} finally {
    //这里的代码始终都会执行
    echo 'Always do this';
}

捕获某种异常的时候只会允许其中一个catch块,如果PHP没有找到适用的catch块,异常会向上冒泡,直到PHP脚本由于致命的错误而终止。
6).异常处理程序。我们可以使用一个全局的异常处理程序,来捕获所有未被捕获的异常。异常捕获程序都必须接受一个了类型为Exception的参数,异常捕获程序使用set_exception_handler()函数注册。

<?php
set_exception_handler(function (Exception $e) {
    //处理并记录异常
});

//你的代码
...

//还原成之前的异常处理程序
restore_exception_handler();
错误

1).我们可以使用error_reporting()函数或者在php.ini文件中使用error_reporting指令告诉PHP报告或者忽略那些错误。这两种都是使用E_*常量来确定。
2)错误报告方式四原则:

  • 一定要让PHP报告错误
  • 在开发环境中要显示错误
  • 再生产环境中不能显示错误
  • 在开发和生产环境中都要记录错误

3)一种php.ini配置的例子:
开发环境:

;显示错误
display_startup_errors = On
display_errors = On
;报告所有错误
error_reporting = -1
; 记录错误
log_errors = On

生产环境:

;不显示错误
display_startup_errors = Off
display_errors = Off
;除了注意事项外,报告所有错误
error_reporting = E_ALL & ~E_NOTICE
; 记录错误
log_errors = On

4).注册全局的错误处理程序:set_error_handler()函数。

<?php
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    //处理错误
    //$errno表示错误等级对应E_*常量
    //$errcontext是一个省略的参数,高级调试才用到
});

5.一个简单的全局错误处理程序的例子:

set_error_handler(function($errno, $errstr, $errfile, $errline) {
   if (!(error_reporting() & $errno)) {
    //error_reporting指令没有设置这个错误,所以忽略
    return;  
  }
  throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});

//其他代码

//还原成之前的错误处理程序
restore_error_handler();
相关处理组件
  • 开发环境: filp/whoops
  • 生产环境: monolog/monolog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant