异常处理与aop精神与番外日志记录

本文详细介绍了如何在PHP中自定义异常处理机制,通过创建BaseException类和ExceptionHandler类来统一异常响应格式,确保API接口的一致性和健壮性。同时,展示了如何使用过滤器进行参数验证,以及编写RESTful风格API的具体实现。

接口编写

首先考虑重新编写异常处理

class BaseException extends Exception
{
    public $code=400;
    public $msg='参数错误';
    public $errorCode=10000;

    public function __construct($params=[])
    {
        if(!is_array($params)){
            return;
        }
        if(array_key_exists('code',$params))
        {
            $this->error=$params['code'];
        }
         if (array_key_exists('msg',$params)){
            $this->msg=$params['msg'];
        }
        if (array_key_exists('errorCode',$params)){
            $this->errorCode=$params['errorCode'];
        }
    }
}
<?php
/**
 * Created by PhpStorm.
 * User: 74985
 * Date: 2018/9/29
 * Time: 11:24
 */

namespace app\lib\exception;


use Exception;
use think\exception\Handle;
use think\Log;
use think\Request;

class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;
    public function render(Exception $e)
    {
        if ($e instanceof BaseException){
            $this->code=$e->code;
            $this->msg=$e->msg;
            $this->errorCode=$e->errorCode;
        }else{
            if (config('app_debug')){
            return parent::render($e);
            }else{
                $this->code=500;
                $this->msg='服务器内部错误';
                $this->errorCode=999;
                $this->recordErrorLog($e);//记录日志
            }
        }
        $request=Request::instance();
        $result=[
            'msg'=>$this->msg,
            'error_code'=>$this->errorCode,
            'request_url'=>$request->url()
        ];
        return json($result,$this->code);
    }
    private function recordErrorLog(Exception $e){
        Log::init([
            'type'=>'File',
            'path'=>LOG_PATH,
            'level'=>['error']//错误级别
        ]);
        Log::record($e->getMessage(),'error');
    }
}

在这里说一下,日志。

把系统原来的关了(config.php log 的type改成‘test’)

然后

define('LOG_PATH',__DIR__.'/../log/');

写进public 的index.php里。

然后运行网页会生成一个日志文件夹。

 

之后写过滤器

<?php
/**
 * Created by PhpStorm.
 * User: 74985
 * Date: 2018/9/27
 * Time: 20:14
 */

namespace app\api\validate;


use app\lib\exception\ParameterException;
use think\Exception;
use think\Request;
use think\Validate;

class BaseValidate extends Validate
{
    public function goCheck()
    {
        $request=Request::instance();
        $params=$request->param();
        $request=$this->batch()->check($params);
        if (!$request){
            $e=new ParameterException([
                'msg'=>$this->error,

            ]);
            $e->msg=$this->error;
            throw $e;
        }else{
            return true;
        }
    }
}
<?php
/**
 * Created by PhpStorm.
 * User: 74985
 * Date: 2018/9/27
 * Time: 20:39
 */

namespace app\api\validate;


class IDMustBePostiveInt extends BaseValidate
{
    protected $rule=[
      'id'=>'require|isPositiveInteger',
        'num'=>'in:1,2,3'
    ];
    protected function isPositiveInteger($value,$rule='',$data='',$field=''){
        if (is_numeric($value)&&is_int($value+0)&&($value+0)>0){
            return true;
        }else{
            return $field.'必须是正整数';
        }
    }
}

然后接口我是这么写的

<?php
/**
 * Created by PhpStorm.
 * User: 74985
 * Date: 2018/9/26
 * Time: 20:03
 */

namespace app\api\controller\v1;


use app\api\validate\IDMustBePostiveInt;
use app\lib\exception\BannerMissException;
use think\Exception;
use think\Validate;
use \app\api\model\Banner as BannerModel;

class Banner
{
    /*
     * 获取id的banner信息
     * @id banner的id号
     * @url /banner/:id
     * @http Get
     * */
    public function getBanner($id)
    {
        (new IDMustBePostiveInt())->goCheck();
            $banner=BannerModel::getBannerByID($id);
            if (!$banner){
//                throw new BannerMissException();
                throw new Exception('内部错误');
            }
        return $banner;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值