ThinkPHP6项目基操(13.实战部分 项目中的自定义异常处理总结 错误页面API错误)
項目中的自定義異常處理總結 錯誤頁面&API錯誤
- 前言
- 一、異常分類
- 1. 控制器找不到
- 2. 方法找不到
- 3. 請求資源不存在
- 4. 系統(tǒng)內(nèi)部異常、HTTP異常等
- 二、異常處理
- 1. 前置處理
- 2. 異常處理詳細代碼
- (1) 控制器找不到
- (2) 方法找不到
- (3) 請求資源不存在及系統(tǒng)錯誤異常
- 三、異常檢測
前言
??一般項目中路由分為返回模板引擎頁面和返回api接口json數(shù)據(jù),兩種方式異常需要返回不同的內(nèi)容,如果是模板引擎頁面遇到異常需要返回錯誤頁面,如果是api接口遇到異常需要返回json數(shù)據(jù)。
??開發(fā)模式和上線模式應該返回不同的內(nèi)容,開發(fā)模式應該盡可能返回具體的錯誤信息,上線模式則不能返回具體的錯誤信息,一般顯示“服務器錯誤,請稍后重試”類似友好的提示,而不是顯示一堆報錯代碼(既不友好又不安全)。
??如果有更好的方法,歡迎提出意見。
一、異常分類
1. 控制器找不到
在訪問路由時,若控制器不對,需要使用空控制器攔截報錯。
2. 方法找不到
方法找不到可以修改app目錄下的BaseController控制器重寫__call方法。
3. 請求資源不存在
自定義攔截報錯信息,可以使用Provider自定義錯誤處理類,重寫render方法,根據(jù)不同的錯誤返回不同的數(shù)據(jù)。
4. 系統(tǒng)內(nèi)部異常、HTTP異常等
同第3點。
二、異常處理
1. 前置處理
(1) .env文件定義APP_DEBUG區(qū)分開發(fā)模式和線上模式,true表示開發(fā)模式,false表示線上模式:
APP_DEBUG = true(2) 在app/common.php 文件定義api返回的數(shù)據(jù)格式:
function show($status, $message = 'error', $data = [], $httpStatus = 200){$result = ["status" => $status,"message" => $message,"result" => $data];return json($result, $httpStatus); }(3) 在當前應用下新建一個provider.php,并指定自定義異常處理類:
<?php// 容器Provider定義文件 return ['think\exception\Handle' => 'app\\admin\\exception\\Http', ];(4) 定義狀態(tài)碼配置,可以在config文件夾下新建status.php添加相應的狀態(tài)碼配置:
<?phpreturn ["success" => 1,"error" => 0,"http_status" => ["not_found" => 404,"validate_error" => 422,"internal_error" => 500] ];(5) 準備錯誤頁面(404,500等)
2. 異常處理詳細代碼
(1) 控制器找不到
在app/controller目錄新建Error類(文件名固定為Error):
這里需要注意的是,多應用的控制器應該定義在應用文件夾里,這里定義在app目錄是為了作用于app下全部應用。
<?phpnamespace app\controller;class Error {public function __call($name, $arguments){if(request()->isAjax()){return show(config("status.error"), env('app_debug') ? "控制器{$name}找不到" : '當前請求資源不存在,請稍后再試', [], config("status.http_status.not_found"));}else{return view(root_path() . 'public/error/admin/404.html', ['e' => env('app_debug') ? "控制器{$name}找不到" : '當前請求資源不存在,請稍后再試'], config("status.http_status.not_found"));}} }(2) 方法找不到
在app/BaseController.php 控制器添加 __call 方法:
public function __call($name, $arguments){if(request()->isAjax()){return show(config("status.error"), env('app_debug') ? "找不到{$name}方法" : '當前請求資源不存在,請稍后再試', [], config("status.http_status.not_found"));}else{return view(root_path() . 'public/error/admin/404.html', ['e' => env('app_debug') ? "{$name}方法找不到" : '當前請求資源不存在,請稍后再試'], config("status.http_status.not_found"));}}(3) 請求資源不存在及系統(tǒng)錯誤異常
app\\admin\\exception\\Http:
<?phpnamespace app\admin\exception; use ErrorException; use Exception; use InvalidArgumentException; use ParseError; use PDOException; use think\exception\ClassNotFoundException; use think\exception\Handle; use think\exception\HttpException; use think\exception\RouteNotFoundException; use think\Response; use Throwable; use TypeError;class Http extends Handle {/*** Render an exception into an HTTP response.** @access public* @param \think\Request $request* @param Throwable $e* @return Response*/public function render($request, Throwable $e): Response{$returnCode = config("status.error");$returnMessage = "系統(tǒng)異常,請稍后再試";$returnData = [];$httpStatus = 500;if($e instanceof BusinessException){ // 自定義添加的業(yè)務異常$returnMessage = $e->getMessage();$httpStatus = config("status.http_status.business_error");}else if($e instanceof ValidateException){$returnMessage = $e->getError();$httpStatus = config("status.http_status.validate_error");}else if (($e instanceof ClassNotFoundException || $e instanceof RouteNotFoundException) || ($e instanceof HttpException && $e->getStatusCode() == 404)) {$returnMessage = env('app_debug') ? $e->getMessage() : '當前請求資源不存在,請稍后再試';$httpStatus = config("status.http_status.not_found");}else if ($e instanceof Exception || $e instanceof PDOException || $e instanceof InvalidArgumentException || $e instanceof ErrorException || $e instanceof ParseError || $e instanceof TypeError || ($e instanceof HttpException && $e->getStatusCode() == 500)) {$returnMessage = env('app_debug') ? $e->getMessage() : '系統(tǒng)異常,請稍后再試';$httpStatus = config("status.http_status.internal_error");}if(request()->isAjax()){return show($returnCode, $returnMessage, $returnData, $httpStatus);}else{if($httpStatus == config("status.http_status.not_found")){$errorUrl = 'public/error/admin/404.html';}else{$errorUrl = 'public/error/admin/error.html';}return view(root_path() . $errorUrl, ['e'=>$returnMessage], $httpStatus);}} }以上代碼中返回的錯誤信息e,需要在錯誤頁面(404,error)顯示:
<p class="error-message">{$e ?? ''}</p>三、異常檢測
異常檢測分瀏覽器頁面訪問異常和api接口返回異常,還需要檢查開發(fā)模式和線上模式。
Tips: api接口可以使用Postman工具模擬,添加Headers:
Content-Type 為 application/x-www-form-urlencoded
X-Requested-With 為 xmlhttprequest
(博主比較懶就不貼截圖了,但是都測試過,同志們自己試一下,算了還是貼一張吧)
??重磅推薦:免費商用電商系統(tǒng)
😏想白嫖整個電商系統(tǒng)用來商用?
🤑想有自己的商城實現(xiàn)財富自由?
🤓想學習最佳實踐提升自己技術?
快來進入🚀 傳送門 🚀,開源免費、完整示例帶你快速入門,輕松二開,走上人生巔峰!👨?🎓
總結
以上是生活随笔為你收集整理的ThinkPHP6项目基操(13.实战部分 项目中的自定义异常处理总结 错误页面API错误)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有一个php的类库网站_可以compos
- 下一篇: docker pull php7,Doc