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.
Then the information that both front-end and back-end personnel can understand must be json (of course it can also be xml), modify the render method
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; }
Then return the error message in json format
$result = [ 'msg' => $this->msg, 'error_code' => $this->errorCode, 'request_url' => request()->url() ]; return json($result,$this->code);
At this point, the global exception handling has been written. Now code it in product.php for testing
public function getProduct($id) { //处理程序运行时错误 /*try{ 3/0; } catch(Exception $ex){ throw $ex; }*/ //处理用户行为产生的错误 $error=[ 'msg'=>'没有找到合适的产品' ]; $ex=new ProductNotFoundException($error); throw $ex; }
##Tips:Don’t forget to change app_debug to false for production environment
Related recommendations :The above is the detailed content of Detailed explanation of exception handling in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment