接口编写
首先考虑重新编写异常处理
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;
}
}