異常處理
和PHP默(mo)認的(de)異常(chang)處(chu)理不(bu)同,ThinkPHP拋出的(de)不(bu)是單純的(de)錯誤信息,而是一個(ge)人性化的(de)錯誤頁面。
默認異常處理
在調(diao)試模(mo)式下,系統默認展示(shi)的(de)錯誤頁面:

只有(you)在調試模式下(xia)面(mian)才能顯示具體(ti)的(de)錯誤信息(xi),如(ru)果在部署模式下(xia)面(mian),你可能看(kan)到的(de)是一個簡單(dan)的(de)提(ti)示文字,例如(ru):

本著嚴謹的原則,5.0版本默認情況下會對任何錯誤(包括警告錯誤)拋出異常,如果不希望如此嚴謹的拋出異常,可以在應用公共函數文件中或者配置文件中使用
error_reporting方法設置錯誤報錯級別(請注意,在入口文件中設置是無效的),例如:
// 異常錯誤報(bao)錯級(ji)別,
error_reporting(E_ERROR | E_PARSE );
異常處理接管
框架支持異常頁面由開發者自定義類進行處理,需要配置參數exception_handle
// 異常處理handle類 留空使用 \think\exception\Handle
'exception_handle' => '\\app\\common\\exception\\Http',
自定義類需要繼承Handle并且實現render方法,可以參考如下代碼:
<?php
namespace app\common\exception;
use Exception;
use think\exception\Handle;
use think\exception\HttpException;
class Http extends Handle
{
public function render(Exception $e)
{
// 參數驗證錯(cuo)誤(wu)
if ($e instanceof ValidateException) {
return json($e->getError(), 422);
}
// 請求異(yi)常
if ($e instanceof HttpException && request()->isAjax()) {
return response($e->getMessage(), $e->getStatusCode());
}
//TODO::開發者對異常的操作
//可以在此交由(you)系(xi)統處理
return parent::render($e);
}
}
需要注意的是,如果配置了'exception_handle',且沒有再次調用系統
render的情況下,配置http_exception_template就不再生效,具體可以參考Handle類內實現的功能。
V5.0.11版本開始,可以通過閉包定義的方式簡化異常自定義處理,例如,上面的自定義異常類可以改為直接配置exception_handle參數:
'exception_handle' => function(Exception $e){
// 參數驗證錯誤
if ($e instanceof \think\exception\ValidateException) {
return json($e->getError(), 422);
}
// 請求(qiu)異常
if ($e instanceof \think\exception\HttpException && request()->isAjax()) {
return response($e->getMessage(), $e->getStatusCode());
}
}
部署模式異常
一旦(dan)關(guan)閉調試模式(shi),發生錯(cuo)誤后不會提示(shi)具(ju)體(ti)的錯(cuo)誤信息(xi),如(ru)果(guo)你仍然(ran)希望看到具(ju)體(ti)的錯(cuo)誤信息(xi),那么可以如(ru)下設置:
// 顯示(shi)錯誤信息
'show_error_msg' => true,

異常捕獲
可以使用PHP的異常捕獲進行必要的處理,但需要注意一點,在異常捕獲中不要使用think\Controller類的error、success和redirect方法,因為上述三個方法會拋出HttpResponseException異常(chang),從(cong)而影響正常(chang)的異常(chang)捕獲,例(li)如:
try{
Db::name('user')->find();
$this->success('執行(xing)成(cheng)功(gong)!');
}catch(\Exception $e){
$this->error('執(zhi)行(xing)錯(cuo)誤');
}
應該改成
try{
Db::name('user')->find();
}catch(\Exception $e){
$this->error('執行錯誤');
}
$this->success('執行(xing)成功!');
