thinkphp6异常处理与日志
2022-07-28 14:14:58
140
{{single.collect_count}}

异常处理

目标:返回json格式的异常信息 # url_route_must:true强制路由模式下
thinkphp6内置已了一个app\ExceptionHandle异常处理类可供使用
该类绑定在app目录下面的provider.php文件中,直接修改该类的相关方法即可完成应用的自定义异常处理机制。
在这里插入图片描述
app\ExceptionHandle.php 异常处理类,重新定义render方法即可

#app\ExceptionHandle.php public function render($request, Throwable $e): Response{// app_debug模式下按原thinkphp6异常模式处理异常if (env('app_debug')) {return parent::render($request, $e);}// 自定义json返回错误if ($e instanceof ValidateException) {return json($e->getError(), 422);return json(['code' => 0, 'msg' => $e->getError()], 422);}// 自定义json返回异常if ($e instanceof HttpException && $request->isAjax()) {return json(['code' => 0, 'msg' => $e->getMessage()], $e->getStatusCode());}// 自定义json返回异常if ($e instanceof HttpException) {return json(['code' => 0, 'msg' => $e->getMessage()]);}// 自定义json返回异常return json(['code' => 0, 'msg' => 'Biny服务器错误']);}

目标:访问未定义的路由时返回json格式的信息 # url_route_must:false 非强制路由模式下
php think make:controller Error --plain

public function index(){return json(['code' => 0,'data' => 'Route is Not Found','msg' => 'success']);}public function __call($name, $arguments){return json(['code' => 0,'data' => 'Route is Not Found','msg' => 'success']);}

日志

DEBUG模式下默认记录error级别和sql执行语句日志
非DEBUG模式默认仅记录error级别日志
DEBUG模式在根目录增加.env文件 设置APP_DEBUG = false/true
在这里插入图片描述

手动记录日志

方法描述
record()Log::record(‘record方法记录的日志信息不是实时保存的’,‘info’);
write()Log::write(‘要实时记录的话,可以采用write方法’,‘info’);

系统在请求结束后会自动调用Log::save方法统一进行日志信息写入

关闭日志

Log::close(); //手动关闭本次请求的日志写入

更多日志配置于app\config\log.php文件中配置,参考官方文档配置即可
官方日志文档

回帖
全部回帖({{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 ? '加载中...' : '查看更多评论'}}