配置文件修改
config/app.php
自定義異常接管類出處
'exception_handle' => ‘\app\common\exception\ExceptionHandle',
自定義處理異常方法
寡人的存放目錄為 app/common/exception
ApiException.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
namespace app\common\exception; use Exception; class ApiException extends Exception { /** * 構造函數 */ public function __construct( array $ApiErrConst , Throwable $previous = null) { $code = $ApiErrConst [0]; $message = $ApiErrConst [1]; parent::__construct( $message , $code , $previous ); } } |
ExceptionHandle.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
namespace app\common\exception; use Exception; use think\exception\Handle; use app\common\exception\ApiException; use app\common\err\ApiErrCode; class ExceptionHandle extends Handle { // 引入復用模塊:JSON返回格式 use \app\common\traits\ResponseJson; public function render(Exception $e ) { if ( $e instanceof ApiException) { $code = $e ->getCode(); $message = $e ->getMessage(); } else { $code = $e ->getCode(); if (! $code || $code < 0) { $code = ApiErrCode::ERROR_UNKNOW[0]; } $message = $e ->getMessage() ? $e ->getMessage() : ApiErrCode::ERROR_UNKNOW[1]; } echo $this ->jsonErrorData( $code , $message ); //該方法在下方 // 其他錯誤交給系統處理 // return parent::render($e); } } |
錯誤碼文件
存放目錄:app/common/err
1
2
3
4
5
6
7
8
9
10
11
|
namespace app\common\err; class ApiErrCode { /** * API通用錯誤碼 const 定義常量 * error_code < 1000 */ const ERROR_UNKNOW = [0, "未知錯誤" ]; const ERROR_URL = [1, "接口不存在" ]; ....... } |
復用模塊
針對API接口返回格式
存放目錄:app/common/traits
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
namespace app\common\traits; trait ResponseJson { /** * API接口出現業務異常時時返回 * @author Leo */ public function jsonErrorData( $code , $message , $data = []) { return $this ->jsonResponse( $code , $message , $data ); } /** * API接口請求成功時返回 * @author Leo */ public function jsonSuccessData( $data = []) { return $this ->jsonResponse(200, "Sucess" , $data ); } /** * 返回一個JSON * @author Leo */ private function jsonResponse( $code , $message , $data ) { $content = [ 'code' => $code , 'msg' => $message , 'data' => $data ]; return json_encode( $content ); } } |
頁面調用
1
2
3
4
5
6
7
8
9
10
|
// 文件頭部引入 use app\common\exception\ApiException; use app\common\err\ApiErrCode; // 引入復用模塊:JSON返回格式 use \app\common\traits\ResponseJson; // 示例 public function index() { throw new ApiException(ApiErrCode::ERROR_URL); // 自定義異常拋出 } |
到此這篇關于thinkphp5.1 中使用自定義異常處理類進行接管的文章就介紹到這了,更多相關thinkphp5.1 自定義異常處理類內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/u011867622/article/details/97147228