先新建了一个异常处理接管的类。在application/lib/expection下创建
ExceptionHandler.php
<?php
namespace app\lib\exception;
use Exception;
use think\exception\Handle;
class ExceptionHandler extends Handle
{
public $code;
public $msg;
public $errorCode;
public function render(Exception $e){
if ($e instanceof BaseException) {
$this ->code = $e->code;
$this ->msg = $e->msg;
$this ->errorCode = $e->errorCode;
}else{
// debug开启,显示默认的异常
if (config('app.app_debug')) return parent::render($e);
$this ->code = 500;
$this ->msg = '服务器异常';
$this ->errorCode = '999';
}
$res = [
'msg'=>$this->msg,
'errorCode'=>$this->errorCode
];
return json($res, $this->code);
}
}
然后创建自定义异常BaseException.php 类继承 Exception
<?php
namespace app\lib\exception;
use Exception;
class BaseException extends Exception
{
public $code = 500;
public $msg = '异常';
public $errorCode = 999;
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'];
}
}
最后定义一个公共方法抛出异常
// 异常类输出函数
function TApiException($msg = '异常', $errorCode = 999, $code = 500){
throw new \app\lib\exception\BaseException(['code'=>$code,'msg'=>$msg,'errorCode'=>$errorCode]);
}