Home >PHP Framework >ThinkPHP >This article explains how to customize global exceptions in thinkphp5
The followingthinkphp frameworktutorial column will explain to you how to customize global exceptions in thinkphp5. I hope it will be helpful to friends in need!
In order to return unreasonable json for various errors when writing api, directly use the prompt error page that comes with TP5. For the client, it obviously has no effect, so you need to customize the global exception yourself. .
1. Create a global exception class (used to transmit error messages, status codes, etc.)
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']; } } }
This way, you can give status codes, error messages and custom error codes that cannot be passed. .
2. Create an error handling class
The error handling class inherits from the error handling class that comes with TP5. By overriding the render method, you can customize errors.
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'); } }
3. Modify the configuration config
// 异常处理handle类 留空使用 \think\exception\Handle 'exception_handle' => 'app\lib\exception\ExceptionHandle', // 关闭日志 'log' => [ // 日志记录方式,内置 file socket 支持扩展 // 关闭自动记录日志,请将type设置为test 'type' => 'test', // 日志保存目录 'path' => __DIR__.'/../log/', // 日志记录级别 'level' => ['sql'], ],
4. Use the error class method
// 这里随便创建一个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); } }
Customized error subclass
// 上面第一节,写的 Base 错误类派上用场了。 class UserMissException extends BaseException { /** HTTP 状态码 * @var string */ public $code = '404'; /** 自定义错误码 * @var string */ public $errorCode = '40000'; /** 错误信息 * @var string */ public $msg = '请求的用户不存在'; }
Request this getUser method , error report~ will display
{ "msg": "请求的用户不存在", "errorCode": "40000", "request_url": "/api/v1/user/10" }
other error types, and you can continue to create exception subclasses and define these error attributes.
5. Summary
Not only in the TP5 framework, including the laravel framework, you can also rewrite the render method of the exception class yourself to achieve the error return data or page you want. stencil.
The above is the detailed content of This article explains how to customize global exceptions in thinkphp5. For more information, please follow other related articles on the PHP Chinese website!