我有一张表格。例如,它的登录表单:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('phone', TextType::class, [
'constraints' => [
new NotBlank(),
new Type(['type' => 'string']),
new Length(['max' => 255]),
new ValueExistsInEntity([
'entityClass' => User::class,
'field' => 'phone',
'message' => 'User not found'
])
]
]);
$builder->add('password', TextType::class, [
'constraints' => [
new NotBlank(),
new Type(['type' => 'string']),
new Length(['min' => 8, 'max' => 128])
]
]);
}
如您所见,它有Length
约束。当我将数组发送到表单中的任何字段时,Length
约束会抛出Symfony\\Component\\Validator\\Exception\\UnexpectedTypeException
和500状态代码并显示消息:
类型"字符串","数组"的预期参数给定
有没有办法避免这种情况或将此异常转换为表单验证错误?
答案 0 :(得分:0)
我发现只有解决方案才能创建事件监听器,只是将异常转换为美容错误(对我来说没关系,因为我只开发API,而不是完整堆栈)。
我的异常事件监听器的简化部分:
namespace AppBundle\EventListener;
use AppBundle\Exceptions\FormValidationException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\Validator\Exception\ValidatorException;
class ApiExceptionListener
{
/**
* @var bool
*/
public $isKernelDebug;
public function __construct(bool $isKernelDebug)
{
$this->isKernelDebug = $isKernelDebug;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$throwedException = $event->getException();
$errorBody = [
'code' => $throwedException->getCode(),
'message' => $throwedException->getMessage(),
];
if ($throwedException instanceof ValidatorException) {
$errorBody['message'] = 'Invalid data has been sent';
}
if ($this->isKernelDebug) {
$errorBody['exception'] = [
'class' => get_class($throwedException),
'message' => $throwedException->getMessage(),
'code' => $throwedException->getCode(),
];
}
$event->setResponse(new JsonResponse(['error' => $errorBody]));
}
}
服务:
app.event_listener.api_exception:
class: AppBundle\EventListener\ApiExceptionListener
arguments: ['%%kernel.debug%%']
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 200 }
但我很高兴看到更好的解决方案来处理从Symfony约束中抛出的异常。
答案 1 :(得分:-1)
因为Length
仅是字符串的验证器。对于数组,您必须使用Count
验证程序。
如果要在同一验证器中同时使用数组和字符串,则应实现自己的Custom validator。