1.传统模式自定义异常处理
定义model层分母为0的异常信息
# url /api/model/Index.php
namespace app\api\model;
use think\Exception;
class Index
{
public static function getIndexID($id)
{
try{
1/0;
}
catch (Exception $ex)
{
// TODO: 可以记录日志
throw $ex;
}
return true;
}
}
定义controller层index信息
<?php
namespace app\api\controller;
use app\api\validata\IDMustBePostiveInt;
use app\api\model\Index as IndexModel;
use think\Exception;
class Index
{
public function getindex($id)
{
try
{
$index = IndexModel::getIndexID($id);
}
catch (Exception $ex)
{
$err = [
'error_code' => 10001,
'msg' => $ex->getMessage()
];
return json($err,400);
}
return $index;
}
全局异常处理类
1.定义exception下常员变量信息继承与Exception
<?php
namespace app\lib\exception;
use think\Exception;
class BaseException extends Exception
{
// HTTP 状态码 404,200
public $code;
// 错误具体信息
public $msg;
// 自定义错误码
public $errorCode;
}
2. 定义需验证的成员错误信息
<?php
namespace app\lib\exception;
class BannerMissException extends BaseException
{
public $code = 404;
public $msg = '请求的banner不存在';
public $errorCode = 40000;
}
3. 定义 ExceptionHandle类继承与Handle验证
<?php
namespace app\lib\exception;
use Exception;
use think\exception\Handle;
use think\facade\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{
$this ->code = 500;
$this ->msg = '服务器内部错误';
$this -> errorCode = 999;
}
$request = Request::instance();
$result = [
'msg' => $this -> msg,
'errorCode' => $this ->errorCode,
'request_url' => $request -> url()
];
return json($result,$this ->code);
}
}
使用render方法验证并通过instanceof函数验证是否是自定义异常