thinkphp6的自定义异常处理
2022-07-28 14:14:58
288
{{single.collect_count}}

框架支持异常处理由开发者自定义类进行接管,需要在app目录下面的provider.php文件中绑定异常处理类,例如:

<?phpuse app\ExceptionHandle;use app\Request;// 容器Provider定义文件return ['think\Request'=> Request::class,//'think\exception\Handle' => ExceptionHandle::class,//原来的异常'think\exception\Handle' => '\\app\\exception\\ExecptionHandle'];

然后再app下面新建一个exception文件夹放自定义错误信息

<?php/** * * User: 小贝壳 * Date: 2022/2/27 **/namespace app\exception;use think\facade\Env;use think\exception\Handle;use app\exception\HttpExceptions;use think\Response;use Throwable;class ExecptionHandle extends Handle{private $msg = "未知错误";private $httpCode = 500;private $errorCode = 19999;public function render($request, Throwable $e): Response{//判断在`.env`里面是否开始了调试,开启了调试就原样返回,关闭了调试就返回自定义的json格式的错误信息if(Env::get("APP_DEBUG") == 1){return parent::render($request,$e);}$this->msg = $e->getMessage() ?: $this->msg;//HttpExceptions是继承同级目录下HttpExceptions,代码在下方if ($e instanceof HttpExceptions) {$this->httpCode = $e->getStatusCode() ?: $this->httpCode;}$this->errorCode = $e->getCode() ?: $this->errorCode;$result_data = ['message' => $this->msg,'data' => [],'code' => $this->errorCode];return json($result_data, $this->httpCode);// 其他错误交给系统处理return parent::render($request, $e);}}

同级目录下HttpExceptions 文件

<?php/** * * User: 小贝壳 * Date: 2022/2/27 * Time: 1:42 **/namespace app\exception;use Exception;class HttpExceptions extends \RuntimeException{private $statusCode;private $headers;//主要是重构$code前提,$previous和 $headers在后面方便调用public function __construct(int $statusCode, string $message = '', $code = 0, Exception $previous = null, array $headers = []){$this->statusCode = $statusCode;$this->headers= $headers;parent::__construct($message, $code, $previous);}public function getStatusCode(){return $this->statusCode;}public function getHeaders(){return $this->headers;}}

调用

use app\exception\HttpExceptions;throw new HttpExceptions(404,"自定义错误",'444');
回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}