为了针对书写 api 时,对各类错误返回不通的 json ,直接使用 TP5 自带的提示错误页面,对于客户端而言,明显没有任何的做用,因此须要本身来自定义全局异常。php
use think\Exception;
class BaseException extends Exception {
/** HTTP 状态码 * @var string */
public $code;
/** 自定义错误码 * @var string */
public $errorCode;
/** 错误信息 * @var string */
public $msg;
public function __construct($params=[]) {
if (! $params) {
return ;
}
// 若是传了 code
if ($array_key_exists('code', $code) {
$this->code = $code;
}
// 若是传了 errorCode
if (array_key_exists('errorCode', $params)) {
$this->errorCode = $params['errorCode'];
}
// 若是传了 msg
if (array_key_exists('msg', $params)) {
$this->msg = $params['msg'];
}
}
}
复制代码
这样就能够给以传不通的状态码,错误信息和自定义错误码。laravel
错误处理类,继承于TP5自带的错误处理类,重写该 render 方法,就能够自定义错误。sql
use Exception;
use think\exception\Handle;
use think\Request;
class ExceptionHandle extends Handle {
/** 状态码 * @var */
private $code;
/** 自定义错误码 * @var */
private $errorCode;
/** 错误信息 * @var */
private $msg;
/** 重写 Handle 方法里的Render * @param Exception $e * @return \think\response\Json */
// 注意这里是基类 Exception
public function render(Exception $e) {
if ($e instanceof BaseException) {
//若是是自定义异常,则控制http状态码,不须要记录日志
//由于这些一般是由于客户端传递参数错误或者是用户请求形成的异常
//不该当记录日志
$this->msg = $e->msg;
$this->code = $e->code;
$this->errorCode = $e->errorCode;
} else {
// 若是是服务器未处理的异常,将http状态码设置为500,并记录日志
if (config('app_debug')) {
// 调试状态下须要显示TP默认的异常页面,由于TP的默认页面
// 很容易看出问题
return parent::render($e);
}
$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);
}
/** 错误日志处理 * 这里把config里日志配置的type改成test * @param Exception $e */
private function recordErrorLog(Exception $e) {
// 开启日志
Log::init([
'type' => 'File',
'path' => LOG_PATH,
'level' => ['error']
]);
// 日志记录方法
Log::record($e->getMessage(),'error');
}
}
复制代码
// 异常处理handle类 留空使用 \think\exception\Handle
'exception_handle' => 'app\lib\exception\ExceptionHandle',
// 关闭日志
'log' => [
// 日志记录方式,内置 file socket 支持扩展
// 关闭自动记录日志,请将type设置为test
'type' => 'test',
// 日志保存目录
'path' => __DIR__.'/../log/',
// 日志记录级别
'level' => ['sql'],
],
复制代码
// 这里随便建立一个userControlelr
class UserController extends Controller {
use app\api\model\User;
/** * 根据 id 获取某个用户 */
public function getUser($id) {
$user = User::get($id);
// 若是 $user 为空 抛出自定义的错误,下面有...
if(! $user) {
throw UserMissException();
}
return json($user);
}
}
复制代码
自定义的错误子类json
// 上面第一节,写的 Base 错误类派上用场了。
class UserMissException extends BaseException {
/** HTTP 状态码 * @var string */
public $code = '404';
/** 自定义错误码 * @var string */
public $errorCode = '40000';
/** 错误信息 * @var string */
public $msg = '请求的用户不存在';
}
复制代码
请求这个 getUser 方法,报错~ 就会显示api
{
"msg": "请求的用户不存在",
"errorCode": "40000",
"request_url": "/api/v1/user/10"
}
复制代码
其余的错误类型,也就能够继续建立异常子类,定义这些错误属性。服务器
不光是在TP5的框架,包括laravel框架,也是能够本身从新写异常类Exception的render方法,来达到本身想要的错误返回数据或者是页面模版。app