model 返回一个null
<?php
namespace app\api\model;
use think\Exception;
class Banner
{
public static function getBannerByID($id){
return null;
}
}
controller 抛出异常
<?php
namespace app\api\controller\v1;
use app\api\model\Banner as BannerModel;
use app\api\validate\IDMustBePositiveInt;
use app\lib\exception\BannerMissException;
use think\Exception;
class Banner
{
/**
* 获取指定id的banner信息
* @url/banner/:id
* @http GET
* @id banner的id号
*
*/
public function getBanner($id){
$validate = new IDMustBePositiveInt();
$validate->goCheck();
$banner = BannerModel::getBannerByID($id);
if(!$banner){
throw new BannerMissException();//抛出异常
//必须继承Exception
}
return $banner;
}
}
exception 进行处理
BannerMissException 继承 BaseException, BaseException 继承 Exception。
BannerMissException 代码实现 BaseException 的代码(具体)
写一个类(也就是设置抛出异常的值)之后在ExceptionHandler 里面进行获取到值,进行判断使用户的行为导致的还是服务器导致的异常,进行抛出异常处理操作。
<?php
namespace app\lib\exception;
class BannerMissException extends BaseException
{
public $code = 404;
public $msg = '请求的Banner不存在';
public $errorCode = 40000;
}
BaseException代码(抽象)
<?php
namespace app\lib\exception;
use think\Exception;
class BaseException extends Exception
{
//HTTP 状态码404,200
public $code;
//错误信息
public $mag;
//自定义错误码
public $errorCode;
}
把config.php里面的代码进行修改去执行自己写的异常处理代码
// 异常处理handle类 留空使用 \think\exception\Handle 'exception_handle' => 'app\lib\exception\ExceptionHandler',
<?php
namespace app\lib\exception;
use think\exception\Handle;
use think\Exception;
use think\Request;
use think\Log;
class ExceptionHandler extends Handle
{
private $code;
private $msg;
private $errorCode;
public function render(Exception $e){
//判断$e是否是实例化的Exception类
//如果是用户导致的必然是。他会调用Excetpion->BaseException->BannerMissException.
if($e instanceof BaseException){
$this->code = $e->code;
$this->msg = $e->msg;
$this->errorCode = $e->errorCode;
}else{
$this->code=500;
$this->msg = "服务器内部错误,不能告诉你";
$this->errorCode = 999;
$this->recordErrorLog($e);
}
$request = Request::instance();
$result = [
'msg'=>$this->msg,
'errorCode'=>$this->errorCode,
'request_url'=> $request->url(),
];
return json($result,$this->code);
}
public function recordErrorLog(Exception $e){
Log::init([
'type' => 'File',
'path' => LOG_PATH,
'level' => ['error'],
]);
Log::record($e->getMessage(),'error');
}
}