You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
2.1 KiB
PHP
69 lines
2.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Exception\Handler;
|
|
|
|
use App\Constants\ResultCode;
|
|
use App\Exception\BusinessException;
|
|
use App\Helper\Result;
|
|
use Hyperf\Contract\StdoutLoggerInterface;
|
|
use Hyperf\ExceptionHandler\ExceptionHandler;
|
|
use Hyperf\HttpMessage\Stream\SwooleStream;
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Throwable;
|
|
use Hyperf\Database\Model\ModelNotFoundException;
|
|
|
|
class AppExceptionHandler extends ExceptionHandler
|
|
{
|
|
/**
|
|
* @var StdoutLoggerInterface
|
|
*/
|
|
protected $logger;
|
|
|
|
public function __construct(StdoutLoggerInterface $logger)
|
|
{
|
|
$this->logger = $logger;
|
|
}
|
|
|
|
public function handle(Throwable $throwable, ResponseInterface $response)
|
|
{
|
|
$data = [];
|
|
$code = ResultCode::SERVER_ERROR;
|
|
$message = '';
|
|
$httpCode = 200;
|
|
if ($throwable instanceof BusinessException) {
|
|
$this->stopPropagation();
|
|
$code = $throwable->getCode();
|
|
$message = $throwable->getMessage();
|
|
} elseif ($throwable instanceof ModelNotFoundException) {
|
|
$this->stopPropagation();
|
|
$code = ResultCode::RECORD_NOT_FOUND;
|
|
$message = ResultCode::getMessage($code);
|
|
} else {
|
|
if (config('app_env') == 'dev') {
|
|
$message = $throwable->getMessage();
|
|
$data = [
|
|
'line' => $throwable->getLine(),
|
|
'file' => $throwable->getFile(),
|
|
];
|
|
} else {
|
|
$message = ResultCode::getMessage($code);
|
|
}
|
|
$this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
|
|
$this->logger->error($throwable->getTraceAsString());
|
|
}
|
|
$result = new Result($code, $message, $data);
|
|
return $response
|
|
->withAddedHeader('content-type', 'application/json; charset=utf-8')
|
|
->withStatus($httpCode)
|
|
->withBody(new SwooleStream(strval($result)));
|
|
|
|
}
|
|
|
|
public function isValid(Throwable $throwable): bool
|
|
{
|
|
return true;
|
|
}
|
|
}
|