|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace App\Exception\Handler;
|
|
|
|
|
|
|
|
use App\Constants\ResultCode;
|
|
|
|
use App\Exception\BasicException;
|
|
|
|
use App\Helper\Result;
|
|
|
|
use Hyperf\Context\Context;
|
|
|
|
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 BasicException) {
|
|
|
|
$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);
|
|
|
|
$requestLog = Context::get('requestLog');
|
|
|
|
if ($requestLog) {
|
|
|
|
$requestLog->response_data = json_encode($result->toArray(), JSON_UNESCAPED_UNICODE);
|
|
|
|
$requestLog->response_time = date('Y-m-d H:i:s');
|
|
|
|
$requestLog->save();
|
|
|
|
}
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|