ThinkPHP5.0源码学习之注册错误和异常处理机制


在base.php文件中,用一句代码\think\Error::register();实现错误和异常处理机制的注册。
// 注册错误和异常处理机制 \think\Error::register();   打开library/think/Error.php,register函数如下: /** * 注册异常处理 * @access public * @return void */ public static function register() {     error_reporting(E_ALL);                                 // 设置错误级别     set_error_handler([__CLASS__, 'appError']);             // 设置错误处理方式     set_exception_handler([__CLASS__, 'appException']);     // 设置异常处理     register_shutdown_function([__CLASS__, 'appShutdown']); // 注册关闭函数 } 注:set_error_handler("myError") 、set_exception_handler("myException")、register_shutdown_function("myShutdown")不仅可以接受函数,还可以接受类的方法(公开的静态方法及公开的非静态方法),但需要以数组形式传递,数组的第一个值为“类名”,第二个值为“方法名”。   1、error_reporting() error_reporting() 函数设置当前脚本的错误报告级别,规定报告哪种错误。E_ALL为显示所有的错误和警告信息,类似的级别还有E_ERROR—运行时致命的错误、E_WARNING—运行时非致命的错误、E_NOTICE-—运行时的通知。   2、set_error_handler() set_error_handler指定appError来处理系统错误,捕获错误后把错误以异常的形式抛出。当程序出现错误的时候自动调用appError函数,该函数实例化了一个PHP自带的错误异常类ErrorException,如果符合异常处理的,就将错误信息以异常的形式抛出来,否则将错误信息写入日志中。   3、set_exception_handler() set_exception_handler指定appException来处理用户抛出的异常,如果不是异常,就实例化ThrowableError类,将异常包装起来并抛出。   4、register_shutdown_function() register_shutdown_function指定appShutdown处理超时异常。   到此,框架的错误和异常处理机制就注册完了。   在注册错误和异常处理机制中,都是使用getExceptionHandler方法来获取异常处理的实例。 /** * 获取异常处理的实例 * @access public * @return Handle */ public static function getExceptionHandler() {     static $handle;       if (!$handle) {         // 异常处理 handle         $class = Config::get('exception_handle');           if ($class && is_string($class) && class_exists($class) &&             is_subclass_of($class, "\\think\\exception\\Handle")         ) {             $handle = new $class;         } else {             $handle = new Handle;               if ($class instanceof \Closure) {                 $handle->setRender($class);             }           }     }       return $handle; } 可以看到 $class = Config::get('exception_handle'); 这句代码,也就是可以通过修改配置参数来指定新的异常处理对象。 如果想使用自定义的错误和异常处理机制,首先在application/config.php文件中找到exception_handle的配置: // 异常处理handle类 留空使用 \think\exception\Handle 'exception_handle'       => '', 指错误信息来自于\think\exception\Handle的方法,将其改为自己定义的Exception类: // 异常处理handle类 留空使用 \think\exception\Handle 'exception_handle'       => 'thinkphp\library\exception\ExceptionHandler', 再按照配置新建文件,为thinkphp\library\exception\ExceptionHandler.php,重写这个Handle方法即可: class ExceptionHandler extends Handle {     public function render(Exception $e)     {         return json('这里是自定义的错误');         //return parent::render($e); // TODO: Change the autogenerated stub     } } 这样就可以使用自定义的错误和异常处理机制了。