请问hyperf如何像Thinkphp框架那样通过HttpResponseException那种捕获异常输出到客户端?

请问hyperf如何像Thinkphp框架那样通过HttpResponseException那种捕获异常输出到客户端?

如:我需要返回给客户端的Json是[code=> 1, data=> ['username'=> '张三'], 'msg'=> 'success']这种格式的,如何在hyperf当中通过像Thinkphp框架那样直接从HttpResponseException捕获异常输出到客户端,而不是还需要 return $this->response->json([code=> 1, data=> ['username'=> '张三'], 'msg'=> 'success'])这种格式输出;

阅读 3.4k
1 个回答

自定义异常类


namespace App\Exception;

use Hyperf\Server\Exception\ServerException;

class HttpResponseException extends ServerException
{
    protected $data;

    public function __construct($data, $message = "", $code = 0)
    {
        parent::__construct($message, $code);
        $this->data = $data;
    }

    public function getData()
    {
        return $this->data;
    }
}

新建异常处理器:

namespace App\Exception\Handler;

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

class HttpResponseExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        // 判断异常是不是 HttpResponseException
        if ($throwable instanceof HttpResponseException) {
            // 获取异常里的数据
            $data = $throwable->getData();
            // 转成 JSON 响应
            $response = $response->withAddedHeader('content-type', 'application/json')->withBody(new SwooleStream(json_encode($data)));
        }

        return $response;
    }

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

在控制器里:


use App\Exception\HttpResponseException;

public function someAction()
{
    //...

    // 抛出自定义异常
    throw new HttpResponseException(['code' => 1, 'data' => ['username' => '张三'], 'msg' => 'success']);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进