thinkphp6的自定义异常处理
果子发表于:2022-11-18 10:57:19浏览:717次
使用最新ThinkPHP6.1.0框架,再做异常接管处理时一直找不到原因出错,不能顺利进行很是郁闷,经过不断折腾发现是 provider.php 文件 没有引用 相关文件导致,现在把正确的贴出来大家参考。
1、配置 rpovider.php文件
<?php
use app\ExceptionHandle;
use app\Request;
// 容器Provider定义文件
return [
'think\Request' => Request::class,
'think\exception\Handle' => ExceptionHandle::class,
];
2、配置 ExceptionHandle 文件
<?php
/**
* 统一异常接管
*/
namespace app;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\FuncNotFoundException;
use think\exception\ClassNotFoundException;
use think\exception\ErrorException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\template\exception\TemplateNotFoundException;
use think\db\exception\PDOException;
use think\db\exception\DbException;
use think\Response;
use Throwable;
use think\facade\Log;
use RuntimeException;
/**
* 应用异常处理类
*/
class ExceptionHandle extends Handle
{
private $error_log_db = true; //异常日志是否写入数据库
/**
* Render an exception into an HTTP response.
* @access public
* @param \think\Request $request
* @param Throwable $e
* @return Response
*/
public function render($request, Throwable $e): Response
{
//方法不存在
if ($e instanceof FuncNotFoundException) {
if($request->isAjax()){
return json(['status'=>404,'msg'=>$e->getFunc().'方法不存在']);
}else{
return response($e->getFunc().'控制器不存在', 404);
}
}
//控制器不存在
if ($e instanceof ClassNotFoundException) {
if($request->isAjax()){
return json(['status'=>404,'msg'=>$e->getClass().'控制器不存在']);
}else{
return response($e->getClass().'控制器不存在', 404);
}
}
//模板不存在
if ($e instanceof TemplateNotFoundException) {
return response($e->getTemplate().'模板不存在', 404);
}
//验证器异常
if ($e instanceof ValidateException) {
return json(['status'=>411,'msg'=>$e->getError()]);
}
//pdo异常
if ($e instanceof PDOException) {
return response($e->getMessage(), 500);
}
//db异常
if ($e instanceof DbException) {
return response($e->getMessage(), 500);
}
//error系统层面错误异常
if ($e instanceof ErrorException) {
return response($e->getMessage(), 500);
}
// 请求异常 多为自定义的请求异常
if ($e instanceof HttpException) {
Log::error('错误信息:'.print_r($e->getMessage(),true));
if($e->getStatusCode() == 500 && $this->error_log_db){
event('ExceptionLog', $e->getMessage());
}
return json(['status'=>$e->getStatusCode(),'msg'=>$e->getMessage()]);
}
return parent::render($request, $e);
}
}
3、注意文件位置 app目录下面
推荐文章
- ThinkPHP+uniAPP 公众号线上答题软件答题抽奖赢红包知识竞赛宣传活动链接系统
- iframe嵌套微信公众号不显示最佳解决方案,使用cors-anywhere 解决跨域问题
- TinyMCE version 6.0.1 粘贴稿件自动下载并上传远程图片的代码
- 勾股DEV是一款专为IT研发团队打造的项目管理与团队协作的系统工具
- 微信小程序网络抽奖系统源码,H5在线有奖知识竞赛扫码制作
- 青春的征程:从固原二中到任山河的徒步传奇
- 谷歌浏览器强制跳转到 https 的解决办法
- element ui中表单el-form的label如何设置宽度
- linux系统 var下面log下面文件的以cron开头的大量文件是什么文件,可以删除吗?
- PHP正则表达式