46 lines
1.2 KiB
PHP
46 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Exception\Handler;
|
|
|
|
use App\Exception\ApiException;
|
|
use App\Lib\ApiReturn;
|
|
use Hyperf\ExceptionHandler\ExceptionHandler;
|
|
use Hyperf\HttpMessage\Stream\SwooleStream;
|
|
use Swow\Psr7\Message\ResponsePlusInterface;
|
|
use Throwable;
|
|
|
|
class ApiExceptionHandler extends ExceptionHandler
|
|
{
|
|
/**
|
|
* 注入
|
|
* @param ApiReturn $return
|
|
*/
|
|
public function __construct(private readonly ApiReturn $return) {}
|
|
|
|
/**
|
|
* @param Throwable $throwable
|
|
* @param ResponsePlusInterface $response
|
|
* @return ResponsePlusInterface
|
|
*/
|
|
public function handle(Throwable $throwable, ResponsePlusInterface $response): ResponsePlusInterface
|
|
{
|
|
if ($throwable instanceof ApiException) {
|
|
$result = $this->return->error($throwable->getMessage(),$throwable->getCode());
|
|
|
|
// 阻止异常冒泡
|
|
$this->stopPropagation();
|
|
|
|
return $response->withHeader("Content-Type", "application/json")
|
|
->withStatus(200)
|
|
->withBody(new SwooleStream(json_encode($result, JSON_UNESCAPED_UNICODE)));
|
|
}
|
|
|
|
// 交给下一个异常处理器
|
|
return $response;
|
|
}
|
|
|
|
public function isValid(Throwable $throwable): bool
|
|
{
|
|
return true;
|
|
}
|
|
} |