thinkphp6的自定义异常处理

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

<?php
use 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');
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值