Table of Contents
您可能感兴趣的文章:
Home Backend Development PHP Tutorial Detailed explanation of exception handling in ThinkPHP_php example

Detailed explanation of exception handling in ThinkPHP_php example

Jun 25, 2018 pm 05:01 PM
thinkphp thinkphp5 Exception handling throw an exception

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
Copy after login

Create several properties to define exception information

// http 错误码 
private $code; 
// 自定义异常信息 
private $msg; 
// 自定义错误码 
private $errorCode;
Copy after login

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; }
Copy after login

Next, create a new controller Product, add methods, and test

public function getProduct($id) 
 { 
 try{ 
  3/0; 
 } 
 catch(Exception $ex){ 
  throw $ex; 
 } 
 }
Copy after login

Then add the following route

Route::get("product/:id","api/v1.Product/getProduct");
Copy after login

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',
Copy after login

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']; 
  } 
 } 
}
Copy after login

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; 
}
Copy after login

Handling different exceptions

In the render method, handle the exceptions separately

//分别处理两种不容类型异常:1、用户错误 2.代码与运行时错误 
  if ($ex instanceof BaseException) { 
 
  } else { 
  
  }
Copy after login

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; 
  }
Copy after login

然后以 json 格式返回错误信息

$result = [ 
   'msg' => $this->msg, 
   'error_code' => $this->errorCode, 
   'request_url' => request()->url() 
  ]; 
  return json($result,$this->code);
Copy after login

至此,全局的异常处理就编写好了,下面在 product.php 中编码进行测试

public function getProduct($id) 
 { 
  //处理程序运行时错误 
  /*try{ 
   3/0; 
  } 
  catch(Exception $ex){ 
   throw $ex; 
  }*/ 
  //处理用户行为产生的错误 
  $error=[ 
   'msg'=>'没有找到合适的产品' 
  ]; 
  $ex=new ProductNotFoundException($error); 
  throw $ex; 
 }
Copy after login

提示:生产环境不要忘了将 app_debug 修改为 false

总结

您可能感兴趣的文章:

PHP7基于curl实现的上传图片功能php技巧

PHP区块查询实现方法分析php技巧

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C++ function exceptions and multithreading: error handling in concurrent environments C++ function exceptions and multithreading: error handling in concurrent environments May 04, 2024 pm 04:42 PM

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.

How does C++ exception handling support custom error handling routines? How does C++ exception handling support custom error handling routines? Jun 05, 2024 pm 12:13 PM

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.

What is the relationship between recursive calls and exception handling in Java functions? What is the relationship between recursive calls and exception handling in Java functions? May 03, 2024 pm 06:12 PM

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.

How to handle exceptions in C++ Lambda expressions? How to handle exceptions in C++ Lambda expressions? Jun 03, 2024 pm 03:01 PM

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.

Exception handling in C++ technology: How to handle exceptions correctly in a multi-threaded environment? Exception handling in C++ technology: How to handle exceptions correctly in a multi-threaded environment? May 09, 2024 pm 12:36 PM

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: understand system behavior through exception tracking PHP exception handling: understand system behavior through exception tracking Jun 05, 2024 pm 07:57 PM

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.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

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.

Exception handling in C++ technology: How to optimize the performance of exception handling? Exception handling in C++ technology: How to optimize the performance of exception handling? May 09, 2024 am 10:39 AM

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.

See all articles