«

hyperf AppExceptionHandler

时间:2024-8-24 23:11     作者:xiang     分类:


<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Exception\Handler;

use App\Util\Response;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use function Hyperf\Support\env;

class AppExceptionHandler extends ExceptionHandler
{
    public function __construct(protected StdoutLoggerInterface $logger)
    {

    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        if(env('APP_ENV')!="production"){
            $format =  Response::fail(500,$throwable->getMessage(),$throwable->getTrace());
        }else{
            $format =  Response::fail(intval(500),"系统错误~");
        }

        return $response->withHeader('created-by', 'xiang')->withStatus(200)->withBody(new SwooleStream(json_encode($format)));
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}