Home >Backend Development >PHP Tutorial >Detailed explanation of exception handling in ThinkPHP_php example
Different from PHP's default exception handling, ThinkPHP throws not a simple error message, but a humanized error page. The following article mainly introduces relevant information about exception handling in ThinkPHP. The article passes The sample code is introduced in very detail. Friends who need it can refer to it
What is an exception
From a broader perspective, exceptions include There are two aspects. On the one hand, there are exceptions caused by syntax and runtime errors during program execution. On the other hand, correct feedback is not given. For example, if the client wants to query a certain product, but it is not found, I think this is also abnormal. A sort of.
The first exception TP framework itself will output error information on the page, but the second exception will generally not output any information, so it is very inconvenient to debug.
This article will introduce the relevant content about ThinkPHP exception handling in detail, and share it for everyone's reference and study. I won't say much below, let's take a look at the detailed introduction.
Prerequisite environment
Now PHP often provides interfaces for the front end, so our exception handling is also based on this.
In the development stage, TP's original exception handling is to output exception information on the page, which can meet the needs. However, in the production environment, exceptions need to be handled in other ways.
This article is all about exception handling in the production environment
AOP programming
Now in many languages, the AOP programming idea is very popular, that is, the aspect-oriented programming idea, popular In other words, it is to handle problems in a unified way instead of handling multiple problems in the same way. For exception handling, it is to define unified exception information and handle it in a unified way
General idea
Customize the exception handling class, override the render method of the default exception handling class, and then configure the custom exception handling class to handle all exceptions
Code implementation
Create the directory exception in the root directory and create ExceptionHandle.php under it. This class should inherit the handle class
class ExceptionHandler extends Handle
Create several properties to define exception information
// http 错误码 private $code; // 自定义异常信息 private $msg; // 自定义错误码 private $errorCode;
Override the render method in the Handle class, when we When the throw new Exception() method is used in the code to throw exception information, the render method is actually called, so we need to rewrite this method to return our own information
public function render(Exception $ex) { return json(['msg'=>"自定义异常信息"]); nbsp; }
Next, create a new controller Product, add methods, and test
public function getProduct($id) { try{ 3/0; } catch(Exception $ex){ throw $ex; } }
Then add the following route
Route::get("product/:id","api/v1.Product/getProduct");
Enter the following url to test
http://z.cn/product/2
The page output result is as follows
It can be seen that it does not execute the custom exception handling function.
Use custom exception handling
Modify the following configuration in config.php
// 异常处理handle类 留空使用 \think\exception\Handle 'exception_handle' => 'app\lib\exception\ExceptionHandler',
Then run
Custom exception handling class
The first type of exception is an exception caused by user behavior. For example, no data that meets the conditions is found (from another perspective, this is not actually an exception). The first type of error is a runtime error. Exceptions caused by users may be divided into many types, so related classes need to be customized.
First define a parent class
class BaseException extends Exception { //http 状态码 public $code; //错误具体消息 public $msg; //自定义错误码 public $errorCode; //构造函数用于接收传入的异常信息,并初始化类中的属性 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']; } } }
Then define an exception handling class that handles product information not found, Used to override various attributes in the parent class, and the attribute information in this class may also be modified, such as msg
class ProductNotFoundException extends BaseException { //http 状态码 public $code = 404; //错误具体消息 public $msg = "请求的产品不存在"; //自定义错误码 public $errorCode = 40000; }
Handling different exceptions
In the render method, handle the exceptions separately
//分别处理两种不容类型异常:1、用户错误 2.代码与运行时错误 if ($ex instanceof BaseException) { } else { }
Instructions: In throw When an exception occurs, the render function will be executed, and the thrown exception object will be copied to the parameter $ex, so the exception type can be determined based on this parameter.
The key now is the production environment, so we hope to return the exception information, Front-end personnel can understand it, instead of outputting error information on the page as above, including stack information, etc.
那么前前端贺后端人员都能够看懂的信息一定是 json(当然也可以是xml)了,修改 render 方法
if ($ex instanceof BaseException) { $this->code = $ex->code; $this->msg = $ex->msg; $this->errorCode = $ex->errorCode; } else { //这里是在运行时产生的各种异常,所以无法准确输出异常信息,所以只能统一输出是服务器错误信息 $this->code = 500; $this->msg = "服务器内部错误"; $this->errorCode = 999; }
然后以 json 格式返回错误信息
$result = [ 'msg' => $this->msg, 'error_code' => $this->errorCode, 'request_url' => request()->url() ]; return json($result,$this->code);
至此,全局的异常处理就编写好了,下面在 product.php 中编码进行测试
public function getProduct($id) { //处理程序运行时错误 /*try{ 3/0; } catch(Exception $ex){ throw $ex; }*/ //处理用户行为产生的错误 $error=[ 'msg'=>'没有找到合适的产品' ]; $ex=new ProductNotFoundException($error); throw $ex; }
提示:生产环境不要忘了将 app_debug 修改为 false
总结
PHP5.0~5.6 各版本兼容性cURL文件上传功能实例分析php技巧
The above is the detailed content of Detailed explanation of exception handling in ThinkPHP_php example. For more information, please follow other related articles on the PHP Chinese website!