多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## php异常托管 和 错误托管 跟 `php` 的 自动加载差不多。 `spl_register_autoload`: 类找不到,将调用此函数。 `set_exception_handler`: 异常,将调用此函数。 `set_error_handler`: 错误将调用此函数。 `session_set_save_handler`: `session` 调用此函数。 .... 分别可以说是: `类找不到托管` `异常托管` `错误托管` `session托管` (`自定义session` 本教程不写) 本篇讲的是: `异常托管` 和 `错误托管` ## 创建core/HandleExceptions.php ``` <?php namespace core; use App\exceptions\ErrorMessageException; use App\exceptions\RunErrorException; use Throwable; class HandleExceptions { // 要忽略记录的异常 不记录到日志去 protected $ignore = [ ]; public function init() { // 所有异常到托管到handleException方法 set_exception_handler([$this, 'handleException']); // 所有错误到托管到handleErorr方法 set_error_handler([$this,'handleErorr']); } // 见:https://www.runoob.com/php/php-error.html public function handleErorr($error_level, $error_message, $error_file,$error_line,$error_context) { // app函数见: "添加函数文件helpers.php" 这篇文章 app('response')->setContent( '死机 都死机 自动开机 关机 重启再死机 三星手机 苹果手机 所有都死机 全世界只剩小米.....' )->setCode(500)->send(); // 记录到日志 app('log')->error( $error_message.' at '.$error_file.':'.$error_file ); } // 异常托管到这个方法 public function handleException(Throwable $e) { if( method_exists($e,'render')) // 如果自定义的异常类存在render()方法 app('response')->setContent( $e->render() )->send(); if(! $this->isIgnore($e)){ // 不忽略 记录异常到日志去 app('log')->debug( $e->getMessage().' at '.$e->getFile().':'.$e->getLine() ); // 显示给开发者看 以便查找错误 echo $e->getMessage().' at '.$e->getFile().':'.$e->getLine(); } } // 是否忽略异常 protected function isIgnore(Throwable $e) { foreach ($this->ignore as $item) if( $item == get_class($e)) return true; return false; } } ``` ## 创建app/exceptions/HandleExceptions.php 继承基础的异常处理类,因为 `core` 的代码一般不给用户改。 让客户去改 `app`文件夹的代码。 ``` <?php namespace App\exceptions; use core\HandleExceptions as BaseHandleExceptions; class HandleExceptions extends BaseHandleExceptions { // 要忽略记录的异常 不记录到日志去 protected $ignore = [ ErrorMessageException::class ]; } ``` ## 绑定到容器 ![](https://img.kancloud.cn/34/10/3410207e1e9f883137940b9ca16bdb40_882x379.png) ## 启动异常 错误托管 ![](https://img.kancloud.cn/6c/ef/6cef81cde2ecc088a7ec3cd38d9e3503_544x222.png) 至此已经完成了,接下来运行下异常。 ## 运行异常 ### 创建app/exceptions/ErrorMessageException.php ``` <?php namespace App\exceptions; use Exception; // 错误消息返回 class ErrorMessageException extends Exception { public function render() { return [ 'data' => $this->getMessage(), 'code' => 400 ]; } } ``` ### 取消这个异常的记录app/exceptions/HandleExceptions.php ![](https://img.kancloud.cn/61/1a/611aa51a7fedef0a25d6f8137f4f51bb_451x380.png) ### 运行 ![](https://img.kancloud.cn/93/d7/93d7fe346f4520c2c8f514682219581b_1080x133.png) ![](https://img.kancloud.cn/43/a8/43a87edf72f3c6b9607b32b23037fcf1_780x253.png) ## 运行错误 ![](https://img.kancloud.cn/9b/b7/9bb7fd16d2190044eac78fe845ad400c_422x112.png) ![](https://img.kancloud.cn/83/7a/837a34e3070125535c69ce20bd7a91b8_759x237.png) ![](https://img.kancloud.cn/ef/a8/efa83bbe4e492444f09bec61ddd50734_1913x817.png)