ThinkPHP6 项目笔记

安装TP6

composer create-project topthink/think tp

开启TP6多应用模式

composer require topthink/think-multi-app

安装thinkphp模板引擎

composer require topthink/think-view

安装验证码扩展

composer require topthink/think-captcha

自定义全局异常处理类

\extend目录下新建扩展exception自定义 ExceptionHandler 继承TPthink\exception\Handle类,在ExceptionHandler类中重写render方法

public function render($request, Throwable $e): Response {
    if ($e instanceof BaseException) {
        // 自定义异常走的逻辑
        $this->code = $e->getCode();
        $this->message = $e->getMessage();
        $this->errorCode = $e->getErrorCode();
    } else {
        // 服务器异常逻辑,不需要将具体错误信息展示给用户
        $this -> code = 500;
        $this -> message = '服务器内部错误';
        $this -> errorCode = 999;
     // 此处要记录日志,留待之后添加
    }
    $result = [
        'message' => $this->message,
        'errorCode' => $this->errorCode,
        'request_url' => Request::url(),
    ];
    return json($result, $this->code);
}

使自定义全局异常生效:

app目录下的provider.php 中定义容器:

'think\exception\Handle' => \exception\ExceptionHandler::class,

定义BaseException 继承 think\Exception ,定义存储错误信息的成员变量

// HTTP 状态码
protected $code = 400;
// 错误具体信息
protected $message = '参数错误';
// 自定义错误码
protected $errorCode = 10000;  

重写__construct()方法,让自定义异常处理类接收一个数组参数

public function __construct($params = []) {
    if (!is_array($params)){
        throw new Exception('参数必须是数组');
    }

    if (array_key_exists('code',$params)){
        $this -> code = $params['code'];
    }
    if (array_key_exists('message',$params)){
        $this -> message = $params['message'];
    }
    if (array_key_exists('errorCode',$params)){
        $this -> errorCode = $params['errorCode'];
    }
}

 

构建验证层

validate目录下定义 BaseValidate继承think\Validate实现gocheck方法

public function goCheck(){
    $params = Request::param();

    $result = $this -> check($params);
    if (!$result){
        throw new \exception\ParamsException([
            'message'=> $this -> error,
            'code' => 400
        ]);
    }else{
        return true;
    }

}

其他的validate文件继承BaseValidate,如 LoginCheck 继承BaseValidate

在控制器里就可以通过 (new LoginCheck()) ->goCheck(); 实现参数校验

校验不通过则抛出自定义异常

 

 

 

 

posted @ 2021-03-26 11:12  高小孬  阅读(346)  评论(0)    收藏  举报