【发布时间】:2022-10-22 03:15:15
【问题描述】:
我是 API 平台的新手,我需要验证路由的 ID 参数以验证它是否是 Symfony/API 平台应用程序上的整数。
当我查询GET /api/customers/{id} 时,我想检查 {id} 的值,如果它无效则抛出异常。
例如:
GET /api/customers/10
它按预期工作,如果资源不存在,我会收到 HTTP 200 状态代码或 404 Not Found。
GET /api/customers/abc 或 GET /api/customers/-1
返回 404 Not Found 错误,但在这种情况下,我想返回 400 Bad Request 错误。我该怎么做呢?
我关注了documentation,并创建了一个这样的 EventSubscriber:
// src/EventSubscriber/CustomerManager.php
final class CustomerManager implements EventSubscriberInterface
{
/**
* @return array[]
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['checkCustomerId', EventPriorities::PRE_VALIDATE],
];
}
/**
* Check the customer ID on GET requests
*
* @param ViewEvent $event
* @return void
* @throws MalformedIdException
*/
public function checkCustomerId(ViewEvent $event)
{
$customer = $event->getControllerResult();
if (!$customer instanceof Customer || !$event->getRequest()->isMethodSafe(false)) {
return;
}
$id = $event->getRequest()->query->get('id');
if (!ctype_digit($id)) {
throw new MalformedIdException(sprintf('"%s" is not a valid customer ID', $id));
}
}
}
我试图改变优先级,但没有任何反应。
我已经创建并注册了我的新异常:
// src/Exception/MalformedIdException.php
namespace App\Exception;
final class MalformedIdException extends \Exception
{
}
api_platform:
# ...
exception_to_status:
# The 4 following handlers are registered by default, keep those lines to prevent unexpected side effects
Symfony\Component\Serializer\Exception\ExceptionInterface: 400 # Use a raw status code (recommended)
ApiPlatform\Core\Exception\InvalidArgumentException: !php/const Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST
ApiPlatform\Core\Exception\FilterValidationException: 400
Doctrine\ORM\OptimisticLockException: 409
# Validation exception
ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException: !php/const Symfony\Component\HttpFoundation\Response::HTTP_UNPROCESSABLE_ENTITY
# Custom mapping
App\Exception\MalformedIdException: 400
我也尝试过在客户实体上使用断言,但这也不起作用。
当我使用php bin/console debug:event kernel.view 时,一切似乎都正常:
------- --------------------------------------------------------------------------- ----------
Order Callable Priority
------- --------------------------------------------------------------------------- ----------
#1 App\EventSubscriber\CustomerManager::checkCustomerId() 65
#2 ApiPlatform\Core\Validator\EventListener\ValidateListener::onKernelView() 64
#3 ApiPlatform\Core\EventListener\WriteListener::onKernelView() 32
#4 ApiPlatform\Core\EventListener\SerializeListener::onKernelView() 16
#5 ApiPlatform\Core\EventListener\RespondListener::onKernelView() 8
------- --------------------------------------------------------------------------- ----------
我错过了什么?
【问题讨论】:
标签: php symfony api-platform.com