


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!

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



Function exception handling in C++ is particularly important for multi-threaded environments to ensure thread safety and data integrity. The try-catch statement allows you to catch and handle specific types of exceptions when they occur to prevent program crashes or data corruption.

C++ exception handling allows the creation of custom error handling routines to handle runtime errors by throwing exceptions and catching them using try-catch blocks. 1. Create a custom exception class derived from the exception class and override the what() method; 2. Use the throw keyword to throw an exception; 3. Use the try-catch block to catch exceptions and specify the exception types that can be handled.

Exception handling in recursive calls: Limiting recursion depth: Preventing stack overflow. Use exception handling: Use try-catch statements to handle exceptions. Tail recursion optimization: avoid stack overflow.

Exception handling in C++ Lambda expressions does not have its own scope, and exceptions are not caught by default. To catch exceptions, you can use Lambda expression catching syntax, which allows a Lambda expression to capture a variable within its definition scope, allowing exception handling in a try-catch block.

In multithreaded C++, exception handling follows the following principles: timeliness, thread safety, and clarity. In practice, you can ensure thread safety of exception handling code by using mutex or atomic variables. Additionally, consider reentrancy, performance, and testing of your exception handling code to ensure it runs safely and efficiently in a multi-threaded environment.

PHP exception handling: Understanding system behavior through exception tracking Exceptions are the mechanism used by PHP to handle errors, and exceptions are handled by exception handlers. The exception class Exception represents general exceptions, while the Throwable class represents all exceptions. Use the throw keyword to throw exceptions and use try...catch statements to define exception handlers. In practical cases, exception handling is used to capture and handle DivisionByZeroError that may be thrown by the calculate() function to ensure that the application can fail gracefully when an error occurs.

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

In order to optimize exception handling performance in C++, the following four techniques can be implemented: Avoid unnecessary exception throwing. Use lightweight exception classes. Prioritize efficiency and design exception classes that contain only necessary information. Take advantage of compiler options to achieve the best balance of performance and stability.
