Skip to content

Commit

Permalink
优化异常处理的错误信息显示
Browse files Browse the repository at this point in the history
  • Loading branch information
yunwuxin committed Aug 13, 2024
1 parent 6259165 commit 1629cd2
Showing 1 changed file with 29 additions and 12 deletions.
41 changes: 29 additions & 12 deletions src/think/exception/Handle.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
namespace think\exception;

use Exception;
use ReflectionClass;
use think\App;
use think\console\Output;
use think\db\exception\DataNotFoundException;
Expand All @@ -35,6 +34,10 @@ class Handle
ValidateException::class,
];

protected $showErrorMsg = [

];

public function __construct(protected App $app)
{
}
Expand Down Expand Up @@ -148,6 +151,22 @@ protected function convertExceptionToArray(Throwable $exception): array
return $this->app->isDebug() ? $this->getDebugMsg($exception) : $this->getDeployMsg($exception);
}

/**
* 是否显示错误信息
* @param \Throwable $exception
* @return bool
*/
protected function isShowErrorMsg(Throwable $exception)
{
foreach ($this->showErrorMsg as $class) {
if ($exception instanceof $class) {
return true;
}
}

return false;
}

/**
* 获取部署模式异常数据
* @access protected
Expand All @@ -156,20 +175,18 @@ protected function convertExceptionToArray(Throwable $exception): array
*/
protected function getDeployMsg(Throwable $exception): array
{
$data = [
'code' => $this->getCode($exception),
'message' => $this->getMessage($exception),
];

$reflectionClass = new ReflectionClass($exception);
$alwaysMsg = $reflectionClass->getAttributes(AlwaysErrorMsg::class);

if (empty($alwaysMsg) && !$this->app->config->get('app.show_error_msg')) {
$showErrorMsg = $this->isShowErrorMsg($exception);
if ($showErrorMsg || $this->app->config->get('app.show_error_msg', false)) {
$message = $this->getMessage($exception);
} else {
// 不显示详细错误信息
$data['message'] = $this->app->config->get('app.error_message');
$message = $this->app->config->get('app.error_message');
}

return $data;
return [
'code' => $this->getCode($exception),
'message' => $message,
];
}

/**
Expand Down

0 comments on commit 1629cd2

Please sign in to comment.