异常处理
目标:返回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文件中配置,参考官方文档配置即可
官方日志文档