在ThinkPHP中,可以通过配置文件来进行错误处理和日志记录。
错误处理:
config.php
中设置app_debug
为false
,即关闭调试模式,开启生产环境模式下的错误处理。// 关闭调试模式
'app_debug' => false,
config.php
中设置exception_handle
为异常处理类的名称,即自定义的异常处理类。// 自定义异常处理类
'exception_handle' => '\app\exception\ExceptionHandler',
ExceptionHandle
类,继承\think\exception\Handle
类,并重写render
方法,对特定异常进行处理。namespace app\exception;
use Exception;
use think\exception\Handle;
use think\Response;
class ExceptionHandler extends Handle
{
public function render(Exception $e): Response
{
if ($e instanceof \think\exception\HttpException && $e->getStatusCode() == 404) {
return response('页面不存在', 404);
}
// 其他错误交给系统处理
return parent::render($e);
}
}
日志记录:
config.php
中设置log
为true
,即开启日志记录。// 开启日志记录
'log' => true,
\think\facade\Log
类提供的方法记录日志,例如Log::write('错误信息', 'error')
。use think\facade\Log;
try {
// 代码块
} catch (Exception $e) {
Log::write('发生错误:' . $e->getMessage(), 'error');
}
以上就是在ThinkPHP中进行错误处理和日志记录的基本步骤和关键词。其中,关闭调试模式、自定义异常处理类、开启日志记录和使用\think\facade\Log
类记录日志都是重要的关键词。