1.更改`app\lib\exception`下ExceptionHandler.php文件
~~~
<?php
namespace app\lib\exception;
use Exception;
use think\exception\Handle;
use think\Request;
use think\Log;
class ExceptionHandler extends Handle
{
private $code;
private $msg;
private $errorCode;
public function render(Exception $e)
{
if ($e instanceof BaseException)
{
//如果是自定義異常,則控制http狀態碼,不需要記錄日志
//因為這些通常是因為客戶端傳遞參數錯誤或者是用戶請求造成的異常
//不應當記錄日志
$this->code = $e->code;
$this->msg = $e->msg;
$this->errorCode = $e->errorCode;
}
else{
// 如果是服務器未處理的異常,將http狀態碼設置為500,并記錄日志
if(config('app_debug')){
// 調試狀態下需要顯示TP默認的異常頁面,因為TP的默認頁面
// 很容易看出問題
return parent::render($e);
}
// 如果是服務器未處理的異常,將http狀態碼設置為500,并記錄日志
$this->code = 500;
$this->msg = 'sorry,we make a mistake. (^o^)Y';
$this->errorCode = 999;
$this->recordErrorLog($e);
}
$request = Request::instance();
$result = [
'msg' => $this->msg,
'error_code' => $this->errorCode,
'request_url' => $request = $request->url()
];
return json($result, $this->code);
}
/*
* 將異常寫入日志
*/
private function recordErrorLog(Exception $e)
{
Log::init([
'type' => 'File',
'path' => LOG_PATH,
'level' => ['error']
]);
// Log::record($e->getTraceAsString());
Log::record($e->getMessage(),'error');
}
}
~~~
2.在`app\lib\exception`下新建ParameterException.php文件
~~~
<?php
namespace app\lib\exception;
/**
* 通用參數類異常錯誤
*/
class ParameterException extends BaseException
{
public $code = 400;
public $errorCode = 10000;
public $msg = "invalid parameters";
}
~~~
3.修改驗證器中BaseValidate.php文件
~~~
<?php
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()
{
// 獲取http傳入的參數
// 對這些參數做檢驗
$request = Request::instance();
$params = $request->param();
$result = $this->check($params);
if(!$result){
$e =new ParameterException();
$e->msg=$this->error;
throw $e;
//$error = $this->error;
//throw new Exception($error);
}
else{
return true;
}
}
}
~~~
結果
