This article explains how to customize global exceptions in thinkphp5
The followingthinkphp frameworktutorial column will explain to you how to customize global exceptions in thinkphp5. I hope it will be helpful to friends in need!
In order to return unreasonable json for various errors when writing api, directly use the prompt error page that comes with TP5. For the client, it obviously has no effect, so you need to customize the global exception yourself. .
1. Create a global exception class (used to transmit error messages, status codes, etc.)
use think\Exception; class BaseException extends Exception { /** HTTP 状态码 * @var string */ public $code; /** 自定义错误码 * @var string */ public $errorCode; /** 错误信息 * @var string */ public $msg; public function __construct($params=[]) { if (! $params) { return ; } // 如果传了 code if ($array_key_exists('code', $code) { $this->code = $code; } // 如果传了 errorCode if (array_key_exists('errorCode', $params)) { $this->errorCode = $params['errorCode']; } // 如果传了 msg if (array_key_exists('msg', $params)) { $this->msg = $params['msg']; } } }
This way, you can give status codes, error messages and custom error codes that cannot be passed. .
2. Create an error handling class
The error handling class inherits from the error handling class that comes with TP5. By overriding the render method, you can customize errors.
use Exception; use think\exception\Handle; use think\Request; class ExceptionHandle extends Handle { /** 状态码 * @var */ private $code; /** 自定义错误码 * @var */ private $errorCode; /** 错误信息 * @var */ private $msg; /** 重写 Handle 方法里的Render * @param Exception $e * @return \think\response\Json */ // 注意这里是基类 Exception public function render(Exception $e) { if ($e instanceof BaseException) { //如果是自定义异常,则控制http状态码,不需要记录日志 //因为这些通常是因为客户端传递参数错误或者是用户请求造成的异常 //不应当记录日志 $this->msg = $e->msg; $this->code = $e->code; $this->errorCode = $e->errorCode; } else { // 如果是服务器未处理的异常,将http状态码设置为500,并记录日志 if (config('app_debug')) { // 调试状态下需要显示TP默认的异常页面,因为TP的默认页面 // 很容易看出问题 return parent::render($e); } $this->code = 500; $this->msg = '服务器内部错误,不想告诉你'; $this->errorCode = 999; $this->recordErrorLog($e); } $request = Request::instance(); $result = [ 'msg' => $this->msg, 'errorCode' => $this->errorCode, 'request_url' => $request->url() ]; return json($result, $this->code); } /** 错误日志处理 * 这里把config里日志配置的type改为test * @param Exception $e */ private function recordErrorLog(Exception $e) { // 开启日志 Log::init([ 'type' => 'File', 'path' => LOG_PATH, 'level' => ['error'] ]); // 日志记录方法 Log::record($e->getMessage(),'error'); } }
3. Modify the configuration config
// 异常处理handle类 留空使用 \think\exception\Handle 'exception_handle' => 'app\lib\exception\ExceptionHandle', // 关闭日志 'log' => [ // 日志记录方式,内置 file socket 支持扩展 // 关闭自动记录日志,请将type设置为test 'type' => 'test', // 日志保存目录 'path' => __DIR__.'/../log/', // 日志记录级别 'level' => ['sql'], ],
4. Use the error class method
// 这里随便创建一个userControlelr class UserController extends Controller { use app\api\model\User; /** * 根据 id 获取某个用户 */ public function getUser($id) { $user = User::get($id); // 如果 $user 为空 抛出自定义的错误,下面有... if(! $user) { throw UserMissException(); } return json($user); } }
Customized error subclass
// 上面第一节,写的 Base 错误类派上用场了。 class UserMissException extends BaseException { /** HTTP 状态码 * @var string */ public $code = '404'; /** 自定义错误码 * @var string */ public $errorCode = '40000'; /** 错误信息 * @var string */ public $msg = '请求的用户不存在'; }
Request this getUser method , error report~ will display
{ "msg": "请求的用户不存在", "errorCode": "40000", "request_url": "/api/v1/user/10" }
other error types, and you can continue to create exception subclasses and define these error attributes.
5. Summary
Not only in the TP5 framework, including the laravel framework, you can also rewrite the render method of the exception class yourself to achieve the error return data or page you want. stencil.
The above is the detailed content of This article explains how to customize global exceptions in thinkphp5. For more information, please follow other related articles on the PHP Chinese website!

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope


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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software