Symfony5.4+Api-Platform2.7:错误响应状态码掩码及新增字段需求
解决Api-Platform 2.7 + Symfony 5.4错误响应状态码统一为200的方案
直接通过自定义异常事件监听器拦截Api-Platform的错误响应,修改状态码并添加真实错误码字段,步骤如下:
1. 创建自定义异常监听器
在src/EventListener/ApiErrorListener.php中编写以下代码,优先于Api-Platform自带的异常监听器执行,修改响应内容:
<?php namespace App\EventListener; use ApiPlatform\Core\Bridge\Symfony\Bundle\EventListener\ExceptionListener as ApiPlatformExceptionListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; class ApiErrorListener implements EventSubscriberInterface { private $apiPlatformExceptionListener; public function __construct(ApiPlatformExceptionListener $apiPlatformExceptionListener) { $this->apiPlatformExceptionListener = $apiPlatformExceptionListener; } public static function getSubscribedEvents(): array { // 设置更高优先级,确保先于ApiPlatform的监听器处理 return [ KernelEvents::EXCEPTION => ['onKernelException', 10], ]; } public function onKernelException(ExceptionEvent $event): void { $request = $event->getRequest(); // 仅处理Api-Platform路由请求 if (!$request->attributes->has('_api_resource_class')) { return; } // 先让ApiPlatform生成标准错误响应 $this->apiPlatformExceptionListener->onKernelException($event); $originalResponse = $event->getResponse(); // 跳过成功响应 if (!$originalResponse instanceof JsonResponse || $originalResponse->getStatusCode() < 300) { return; } // 解析原始错误数据 $originalData = json_decode($originalResponse->getContent(), true) ?: []; $realStatusCode = $originalResponse->getStatusCode(); // 注入真实错误码字段 $originalData['code'] = $realStatusCode; // 生成状态码为200的新响应 $newResponse = new JsonResponse($originalData, 200); $event->setResponse($newResponse); } }
2. 确认监听器注册
Symfony 5.4默认开启自动配置,实现EventSubscriberInterface的类会自动注册为事件订阅者。如果未自动生效,可手动在config/services.yaml中添加配置:
App\EventListener\ApiErrorListener: arguments: $apiPlatformExceptionListener: '@api_platform.event_listener.exception' tags: - { name: kernel.event_subscriber }
3. 验证效果
发起一个会触发错误的请求(比如访问不存在的API资源、提交非法参数),此时响应状态码会变为200,JSON结构中会新增code字段,值为原本的错误状态码(如404、400、500等),同时保留Api-Platform生成的原始错误信息。
内容的提问来源于stack exchange,提问作者bakalov85
相关产品推荐
相关产品推荐

