ThinkPhp5.1-自定义异常【完整版】

{
    "code": 400,
    "msg": "自定义异常信息",
    "error_code": 10000,
    "request": "/userapi/v1/banner?email=15555@qq.com"
}

①:

// 异常处理handle类 留空使用 \think\exception\Handle【注意路径】
    'exception_handle'       => '\\app\\common\\exception\\ExceptionHandle',

自定义类需要继承think\exception\Handle并且实现render方法

【BaseException】异常基类

<?php
/**
* Created by PhpStorm.
* User: 14155
* Date: 2019/5/30
* Time: 22:59
*/

namespace app\common\exception;


use think\Exception;

class BaseException extends Exception
{
   public $code = 500;
   public $msg = '系统错误';
   public $errorCode = 999;

   /**
    * 构造函数,接收一个关联数组
    * @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'];
       }
   }
}


【ExceptionHandle】

<?php
/**
* Created by PhpStorm.
* User: 14155
* Date: 2019/5/30
* Time: 22:57
*/

namespace app\common\exception;


use think\Exception;
use think\exception\Handle;
use think\facade\Config;
use think\facade\Log;

class ExceptionHandle extends Handle
{
   private $code;
   private $msg;
   private $errorCode;

   public function render(\Exception $e)
   {
       if ($e instanceof BaseException) {
           //  当前异常属于BaseException时

           $this->code = $e->code;
           $this->msg = $e->msg;
           $this->errorCode = $e->errorCode;
       } else {
           if (Config::get('app_debug')) {
               //  如果当前开启bug调试时,则不做处理,因为会显示比较全的提示错误
               return parent::render($e);
           }

           $this->code = 500;
           $this->mas = 'error';
           $this->errorCode = '999';
           //  写入日志
           $this->recordErrorLog($e);
       }
       $request = \think\facade\Request::instance();
       $result = [
           'msg' => $this->msg,
           'error_code' => $this->errorCode,
           'request' => $request->url(),
       ];

       return json($result,$this->code);
   }

   /**
    * 将异常写入日志
    * @param $e
    */
   protected function recordErrorLog($e)
   {
       //  写入日志操作
//        Log::init([
//            'type'  =>  'File',
//            'path'  =>  LOG_PATH,
//            'level' => ['error']
//        ]);
//        Log::record($e->getTraceAsString());
       Log::record($e->getMessage(),'error');

   }

}

-------------------------------


【ParamBaseException】参数异常

<?php
/**
 * Created by PhpStorm.
 * User: 14155
 * Date: 2019/5/30
 * Time: 23:02
 */

namespace app\common\exception;


class ParamBaseException extends BaseException
{
    public $code = 400;
    public $errorCode = 10000;
    public $msg = 666;

    /**
     * ParamBaseException constructor.
     * @param string $msg
     */
    public function __construct($msg = "参数错误")
    {
        $this->msg = $msg;
    }

}


Tp5自定义日志文件:
// 独立日志级别
    'apart_level' => [
        'demo'
    ],

 Log::record('aaaaaaaabbbbbbbbbbbbbbbbbbaaaaaaaa','demo');
private function setHeader()
    {
        // 公共响应头
        header('Content-Type: Application/json');

        // 如果需要跨域,写在这里
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: x-token,user-type,Origin,Access-Control-Request-Headers,SERVER_NAME,Access-Control-Allow-Headers,cache-control,token, X-Requested-With,Content-Type,Accept,Connection,User-Agent,Cookie');
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');

        // 如果是options请求,直接响应
        if (request()->method() == 'OPTIONS') {
            return '';
        }
    }
    
    ````
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值