【TP5 :錯誤和除錯】異常處理
阿新 • • 發佈:2019-01-31
預設異常處理
在除錯模式下,系統預設展示的錯誤頁面:
在部署模式下面,顯示簡單的提示文字:
// 錯誤顯示資訊,非除錯模式有效
'error_message' => '頁面錯誤!請稍後再試~',
5.0
版本預設對任何錯誤(包括警告錯誤)丟擲異常,可在應用公共函式檔案中或者配置檔案中使用error_reporting
方法設定錯誤報錯級別(在入口檔案中設定是無效的),例:
// 異常錯誤報錯級別,
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)
{
// 引數驗證錯誤
if ($e instanceof ValidateException) {
return json($e->getError(), 422);
}
// 請求異常
if ($e instanceof HttpException && request()->isAjax()) {
return response($e->getMessage(), $e ->getStatusCode());
}
//TODO::開發者對異常的操作
//可以在此交由系統處理
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);
}
// 請求異常
if ($e instanceof \think\exception\HttpException && request()->isAjax()) {
return response($e->getMessage(), $e->getStatusCode());
}
}
部署模式異常
關閉除錯模式,發生錯誤後不會提示具體的錯誤資訊,如果你仍然希望看到具體的錯誤資訊,那麼可以如下設定:
// 顯示錯誤資訊
'show_error_msg' => true,
異常捕獲
可使用PHP的異常捕獲進行必要的處理,但在異常捕獲中不要使用think\Controller
類的error
、success
和redirect
方法,因為上述三個方法會丟擲HttpResponseException
異常,從而影響正常的異常捕獲,例:
try{
Db::name('user')->find();
$this->success('執行成功!');
}catch(\Exception $e){
$this->error('執行錯誤');
}
應該改成
try{
Db::name('user')->find();
}catch(\Exception $e){
$this->error('執行錯誤');
}
$this->success('執行成功!');