美文网首页
TP5 AOP思想应用--构建全局异常层

TP5 AOP思想应用--构建全局异常层

作者: 铁匠简记 | 来源:发表于2018-06-14 10:02 被阅读13次

    AOP :面向切面编程

    个人理解:

    面向切面编程即把项目中相同的功能抽出来成一个层,也就是所说的切面;
    举个例子:去超市购物,超市的出、入口就是每个人都要通过的流程,超市结算也是我们必须通过的,对于超市而言,不可能为我们每个人设置专门的出、入口,更不会为每个人专设一个结算台。抽象超市购物过程为一个项目,每个人的购物行为为项目的某个功能,那么超市的出入口和结算台就是我们的项目的切面,不同的切面可以对应不同的层。
    结合学习,记录一下自己的笔记:

    1、tp5中构建全局异常层,需要重写源码中的异常
    namespace app\lib\exception;
    
    use think\exception\Handle;
    use think\Log;
    use think\Request;
    use Exception;
    
    /*
     * 重写Handle的render方法,实现自定义异常消息
     * 这里捕获的是php的Exception,而不是think的Exception,防止出现httpException
     */
    class ExceptionHandler extends Handle
    {
        private $code;
        private $msg;
        private $errorCode;
    
        public function render(\Exception $e)
         {
            if ($e instanceof BaseException)
            {
                //如果是自定义异常,则控制http状态码,不需要记录日志
                //因为这些通常是因为客户端传递参数错误或者是用户请求造成的异常
                //不应当记录日志
    
                $this->code = $e->code;
                $this->msg = $e->msg;
                $this->errorCode = $e->errorCode;
            }
            else{
                // 如果是服务器未处理的异常,将http状态码设置为500,并记录日志
                if(config('app_debug')){
                    // 调试状态下需要显示TP默认的异常页面,因为TP的默认页面
                    // 很容易看出问题
                    return parent::render($e);
                }
    
                $this->code = 500;
                $this->msg = 'sorry,we make a mistake. (^o^)Y';
                $this->errorCode = 999;
                $this->recordErrorLog($e);
            }
    
            $request = Request::instance();
            $result = [
                'msg'  => $this->msg,
                'error_code' => $this->errorCode,
                'request_url' => $request = $request->url()
            ];
            return json($result, $this->code);
        }
    
        /*
         * 将异常写入日志
         */
        private function recordErrorLog(\Exception $e)
        {
            Log::init([
                'type'  =>  'File',
                'path'  =>  LOG_PATH,
                'level' => ['error']
            ]);
    //        Log::record($e->getTraceAsString());
            Log::record($e->getMessage(),'error');
        }
    }
    
    2、自定义异常类的基类
    namespace app\lib\exception;
    use think\Exception;
    
    /**
     * Class BaseException
     * 自定义异常类的基类
     */
    class BaseException extends Exception
    {
        public $code = 400;
        public $msg = 'invalid parameters';
        public $errorCode = 999;
        
        public $shouldToClient = true;
    
        /**
         * 构造函数,接收一个关联数组
         * @param array $params 关联数组只应包含code、msg和errorCode,且不应该是空值
         */
        public function __construct($params=[])
        {
            if(!is_array($params)){
                return;
            }
            if(array_key_exists('code',$params)){
                $this->code = $params['code'];
            }
            if(array_key_exists('msg',$params)){
                $this->msg = $params['msg'];
            }
            if(array_key_exists('errorCode',$params)){
                $this->errorCode = $params['errorCode'];
            }
        }
    }
    
    3、抛出自定义的异常
    namespace app\lib\exception;
    
    /**
     * token验证失败时抛出此异常 
     */
    class ForbiddenException extends BaseException
    {
        public $code = 403;
        public $msg = '权限不够';
        public $errorCode = 10001;
    }
    

    苦海无边,学无止境!!

    相关文章

      网友评论

          本文标题:TP5 AOP思想应用--构建全局异常层

          本文链接:https://www.haomeiwen.com/subject/dcseeftx.html