Detailed explanation of exception handling in ThinkPHP
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
