<?php
namespace App\Exception\Handler;

use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Snowflake\IdGeneratorInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Hyperf\Di\Annotation\Inject;
use Throwable;

class BusinessExceptionHandler extends  ExceptionHandler
{
    #[Inject]
    protected StdoutLoggerInterface $logger;

    protected string $environment;

    #[Inject]
    protected ContainerInterface $container;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
        $this->environment = env("APP_ENV", 'prod');
    }

    public function handle(Throwable $throwable, ResponseInterface $response): ResponseInterface
    {
        // 判断被捕获到的异常是希望被捕获的异常
        if ($throwable instanceof BusinessException) {
            if ($this->environment != "dev"){
                // 生产环境 固定返回服务器错误
                $message = HttpEnumCode::getMessage(HttpEnumCode::SERVER_ERROR);
            }else{
                $message = $throwable->getMessage();
            }

            $generator = $this->container->get(IdGeneratorInterface::class);
            $id = $generator->generate();

            $data = json_encode([
                'data' => $id,
                'code' => $throwable->getCode(),
                'message' => $message,
            ], JSON_UNESCAPED_UNICODE);
            $this->logger->error($id . "-start");
            $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
            $this->logger->error($throwable->getTraceAsString());
            $this->logger->error($id . "-end");

            // 阻止异常冒泡
            $this->stopPropagation();
            return $response->withStatus(500)->withHeader('content-type', 'application/json; charset=utf-8')->withBody(new SwooleStream($data));
        }

        // 交给下一个异常处理器
        return $response;

        // 或者不做处理直接屏蔽异常
    }

    /**
     * 判断该异常处理器是否要对该异常进行处理
     */
    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}