本文實例講述了Thinkphp5框架異常處理操作。分享給大家供大家參考,具體如下:
異常處理
有時候服務端會報出我們無法感知的錯誤,TP5默認會自動渲染錯誤的形式,生產環境中這樣的形式并不是我們想要的。
未知錯誤
1.exception\Handle.php下的render方法需要覆蓋
創建ApiHandleException.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?php namespace app\common\lib\exception; use think\exception\Handle; class ApiHandleException extends Handle { /** * http 狀態碼 * @var int */ public $httpCode = 500; public function render(\Exception $e ) { return show(0, $e ->getMessage(), [], $this ->httpCode); } } |
2.修改config.php的exception_handle配置項
已知錯誤
我們在判斷一個數據是否合法的時候,若不合法則拋出異常。
例如:
1
2
3
|
if ( $data [ 'msg' ] != 1){ throw Exception( '數據異常' ); } |
使用內置的異常http狀態碼始終為500
1.創建ApiException.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<?php namespace app\common\lib\exception; use think\Exception; class ApiException extends Exception { public $message = '' ; public $httpCode = 500; public $code = 0; /** * @param string $message * @param int $httpCode * @param int $code */ public function __construct( $message = '' , $httpCode = 0, $code = 0) { $this ->httpCode = $httpCode ; $this ->message = $message ; $this ->code = $code ; } } |
2.對ApiHandleException.php改寫
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<?php namespace app\common\lib\exception; use think\exception\Handle; class ApiHandleException extends Handle { /** * http 狀態碼 * @var int */ public $httpCode = 500; public function render(\Exception $e ) { if ( $e instanceof ApiException) { $this ->httpCode = $e ->httpCode; } return show(0, $e ->getMessage(), [], $this ->httpCode); } } |
開發環境
在開發環境的時候依舊使用異常渲染的模式
在ApiHandleException.php中添加代碼
1
2
3
|
if (config( 'app_debug' ) == true) { return parent::render( $e ); } |
希望本文所述對大家基于ThinkPHP框架的PHP程序設計有所幫助。
原文鏈接:https://blog.csdn.net/huangyuxin_/article/details/93641943