Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize global exceptions in thinkphp5

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to customize global exceptions in thinkphp5". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to customize global exceptions in thinkphp5.

For the json that cannot be returned to various errors when writing api, directly use the error page that comes with TP5, which obviously has no effect on the client, so you need to customize the global exception yourself.

1. Create a class with a global exception (for sending error messages, status codes, etc.)

Use think\ Exception;class BaseException extends Exception {/ * * HTTP status code * @ var string * / public $code; / * * Custom error code * @ var string * / public $errorCode; / * * error message * @ var string * / public $msg; public function _ _ construct ($params= []) {if (! $params) {return } / / if code if ($array_key_exists ('code', $code) {$this- > code = $code;} / / if errorCode if (' errorCode', $params)) {$this- > errorCode = $params ['errorCode'] } / / if msg if (array_key_exists ('msg', $params)) {$this- > msg = $params [' msg'];} is passed

This allows you to give impassable status codes, error messages, and custom error codes.

two。 Create an error handling class

The error handling class, which inherits from the error handling class that comes with TP5, can be customized by overriding the render method.

Use Exception;use think\ exception\ Handle;use think\ Request;class ExceptionHandle extends Handle {/ * * status code * @ var * / private $code; / * * Custom error code * @ var * / private $errorCode; / * * error message * @ var * / private $msg / * * override Render * @ param Exception $e * @ return\ think\ response\ Json * / Note here is the base class Exception public function render (Exception $e) {if ($e instanceof BaseException) {/ / if it is a custom exception, control the http status code There is no need to log / / because these are usually due to incorrect parameters passed by the client or exceptions caused by user requests / / should not log $this- > msg = $e-> msg $this- > code = $e-> code; $this- > errorCode = $e-> errorCode } else {/ / if it is an exception not handled by the server, set the http status code to 500and log if (config ('app_debug')) {/ / the default exception page of TP needs to be displayed in debug state Because the default page of TP / / it's easy to see the problem return parent::render ($e) } $this- > code = 500; $this- > msg = 'server internal error, do not want to tell you'; $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) } / * * error log handling * here change the type configured in config to test * @ param Exception $e * / private function recordErrorLog (Exception $e) {/ / enable log Log::init (['type' = >' File', 'path' = > LOG_PATH') 'level' = > [' error']]) / / logging method Log::record ($e-> getMessage (), 'error');}}

3. Modify configuration config

/ / exception handling handle class is left blank using\ think\ exception\ Handle' exception_handle' = > 'app\ lib\ exception\ ExceptionHandle', / / turn off logging' log' = > [/ / logging mode. Built-in file socket supports extension / / turn off automatic logging Please set type to test' type' = > 'test', / / log save directory' path' = > _ _ DIR__.'/../log/', / / logging level 'level' = > [' sql'],]

4. Methods that use the error class

/ / casually create a userControlelrclass UserController extends Controller {use app\ api\ model\ User; / * get a user according to id * / public function getUser ($id) {$user = User::get ($id); / / if $user is empty, throw a custom error. If (! $user) {throw UserMissException ();} return json ($user);}}

Custom error subclass

/ / in the first section above, the Base error class came in handy. Class UserMissException extends BaseException {/ * * HTTP status code * @ var string * / public $code = '404'; / * * Custom error code * @ var string * / public $errorCode = '40000'; / * * error message * @ var string * / public $msg = 'the requested user does not exist';}

Request this getUser method, and the error will be displayed.

{"msg": "the requested user does not exist", "errorCode": "40000", "request_url": "/ api/v1/user/10"}

For other error types, you can continue to create exception subclasses and define these error properties.

At this point, I believe you have a deeper understanding of "how to customize global exceptions in thinkphp5". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report