hyperf 自定義異常處理


控制器 app/Controller/IndexController.php

<?php
namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use App\Exception\FooException;
/**
 * @AutoController();
 */
class IndexController
{
        public function index(){
                throw new FooException('Foo Exception...', 504);
                return 'index';
        }
}

定義異常處理器 app/Exception/Handler/FooExceptionHandler.php

<?php
namespace App\Exception\Handler;

use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use App\Exception\FooException;
use Throwable;

class FooExceptionHandler extends  ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // 判斷被捕獲到的異常是希望被捕獲的異常
        if ($throwable instanceof FooException) {
            // 格式化輸出
            $data = json_encode([
                'code' => $throwable->getCode(),
                'message' => $throwable->getMessage(),
            ], JSON_UNESCAPED_UNICODE);

            // 阻止異常冒泡
            $this->stopPropagation();
            return $response->withStatus(500)->withBody(new SwooleStream($data));
        }

        // 交給下一個異常處理器
        return $response;

        // 或者不做處理直接屏蔽異常
    }

    /**
     * 判斷該異常處理器是否要對該異常進行處理
     */
    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}

定義異常處理類 app/Exception/FooException.php

<?php
namespace App\Exception;

use App\Constants\ErrorCode;
use Hyperf\Server\Exception\ServerException;
use Throwable;

class FooException extends ServerException
{
}

注冊異常處理器 config/autoload/exceptions.php

<?php

declare(strict_types=1);
return [
    'handler' => [
        'http' => [
            Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,
            App\Exception\Handler\AppExceptionHandler::class,
            App\Exception\Handler\FooExceptionHandler::class,
        ],
    ],
];

測試

curl 118.195.173.53:9501/index/index

結果

{"code":504,"message":"Foo Exception..."}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM