tp5中捕獲異常的配置


首選在配置文件中加入配置如下

 

    // 異常處理handle類 留空使用 \think\exception\Handle
    'exception_handle'       => '\\app\\common\\exception\\Http',
    'http_exception_template'    =>  [
        // 定義404錯誤的重定向頁面地址
        404 =>  APP_PATH.'view/error/404.html',
    ],

值得注意的是該配置文件必須是所有模塊的而不是單個的模塊的

目錄結構圖如下

 

 

 

然后在\app\common\exception\Http.php文件中加入以下代碼:

 

<?php
namespace app\common\exception;


use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\Response;
class Http extends Handle
{


    public function render(Exception $e)
    {
        // 參數驗證錯誤
        if ($e instanceof ValidateException) {
            return json($e->getError(), 422);
        }


        // 請求異常
        if ($e instanceof HttpException && request()->isAjax()) {
            return response($e->getMessage(), $e->getStatusCode());
        }


        //TODO::開發者對異常的操作
        if($e->getStatusCode()=='404'){
            return response($e->getMessage(), $e->getStatusCode());
        }
        //可以在此交由系統處理
        return parent::render($e);
    }


}

 

 

然后就可以在編碼中捕捉異常了

try{
Db::name('user')->find();
}catch(\Exception $e){
$this->error('執行錯誤');
}
$this->success('執行成功!');

---------------------
作者:司徒小子
來源:CSDN
原文:https://blog.csdn.net/ruoshui1748/article/details/78032733/
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM