Added Validation to API requests.
CI / Docker Lint (push) Successful in 21s

- Added Symfony Validation Lib.
- Updated API DTOs to include validation constraints.
This commit is contained in:
2024-10-18 20:32:36 +02:00
parent fbee23c022
commit 37462e4646
11 changed files with 75 additions and 67 deletions
+20 -1
View File
@@ -10,6 +10,7 @@ use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Validator\Exception\ValidationFailedException;
class ApiExceptionSubscriber implements EventSubscriberInterface
{
@@ -34,7 +35,25 @@ class ApiExceptionSubscriber implements EventSubscriberInterface
* low-level exception, which should *not* be exposed
*/
if ($e instanceof HttpExceptionInterface) {
$apiErrorMsg->setExtraData('detail', $e->getMessage());
//Check if it's a Validation error.
// When using MapRequestPayload() ValidationErrors throw HttpExceptions.
$prev = $e->getPrevious();
if ($prev instanceof ValidationFailedException) {
//Get validation error details.
$errorList = [];
$violationList = $prev->getViolations();
foreach ($violationList as $violation) {
$errorList[] = [
'field' => $violation->getPropertyPath(),
'message' => $violation->getMessage(),
];
}
$apiErrorMsg->setExtraData('detail', "Validation Error. See errorList for details");
$apiErrorMsg->setExtraData('errorList', $errorList);
} else {
//Get exception error message.
$apiErrorMsg->setExtraData('detail', $e->getMessage());
}
}
}