TP5實現自定義拋出異常消息(關閉debug)


重寫Handle的render方法,實現自定義異常消息-----------------------------------------------------------------------
首先要在config.php里面配置

// 異常處理handle類 留空使用 \think\exception\Handle
'exception_handle' => '\\app\\common\\exception\\ExceptionHandler',



ExceptionHandler
.php


<?php

namespace app\common\exception;

use think\exception\Handle;
use think\Log;
use Exception;

/**
* 重寫Handle的render方法,實現自定義異常消息
* Class ExceptionHandler
* @package app\common\library\exception
*/
class ExceptionHandler extends Handle
{
private $code;
private $message;

/**
* 輸出異常信息
* @param Exception $e
* @return \think\Response|\think\response\Json
*/
public function render(Exception $e)
{
if ($e instanceof BaseException) {
$this->code = $e->code;
$this->message = $e->message;
} else {
if (config('app_debug')) {
return parent::render($e);
}
$this->code = 0;
$this->message = $e->getMessage() ?: '很抱歉,服務器內部錯誤';
$this->recordErrorLog($e);
}
return json(['msg' => $this->message, 'code' => $this->code]);
}

/**
* 將異常寫入日志
* @param Exception $e
*/
private function recordErrorLog(Exception $e)
{
Log::record($e->getMessage(), 'error');
Log::record($e->getTraceAsString(), 'error');
}
}


自定義異常類的基類---------------------------------------------------------------------------------------------
 
BaseException.php
 
        
<?php

namespace app\common\exception;

use think\Exception;

/**
* Class BaseException
* 自定義異常類的基類
*/
class BaseException extends Exception
{
public $code = 0;
public $message = 'invalid parameters';

/**
* 構造函數,接收一個關聯數組
* @param array $params 關聯數組只應包含code、msg,且不應該是空值
*/
public function __construct($params = [])
{
if (!is_array($params)) {
return;
}
if (array_key_exists('code', $params)) {
$this->code = $params['code'];
}
if (array_key_exists('msg', $params)) {
$this->message = $params['msg'];
}
}
}





拋出異常時顯示如下

 

 
        

 

 


免責聲明!

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



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