Skip to content

Commit

Permalink
chore: adjust api message for validation exception
Browse files Browse the repository at this point in the history
  • Loading branch information
albertcht committed Sep 4, 2024
1 parent 9711f0a commit b9bf4b3
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion app/Exceptions/Handlers/ApiExceptionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ public function handle(Throwable $throwable, ResponseInterface $response): Respo
'message' => $this->getMessage($throwable),
];

if ($throwable instanceof ValidationException) {
/* @phpstan-ignore-next-line */
$result['errors'] = $throwable->validator->errors()->toArray();
}

if (environment()->isDebug() && ! environment()->isTesting()) {
$e = FlattenException::createFromThrowable($throwable);
$result['trace'] = $e->getTrace();
Expand Down Expand Up @@ -62,7 +67,12 @@ protected function getStatusCode(Throwable $e): int
protected function getMessage(Throwable $e): string
{
if ($e instanceof ValidationException) {
return $e->validator->errors()->first();
$message = $e->validator->errors()->first();
$errorsCount = $e->validator->errors()->count();
if ($errorsCount > 1) {
$message = $message . ' (and ' . $errorsCount - 1 . ' more errors)';
}
return $message;
}

$message = $message = $e->getMessage() ?? null;
Expand Down

0 comments on commit b9bf4b3

Please sign in to comment.