refactor: extract error response helper and slim json response

Replace multiple catch blocks with single catch(Throwable) funneled through errorResponse() matching the CompanyController pattern. Also clean jsonResponse to accept data+status only, instantiating Response internally.
This commit is contained in:
Yisroel Baum 2026-05-17 09:59:32 +03:00
parent 8a9b35abd3
commit 9661452c75
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9

View file

@ -10,9 +10,11 @@ use App\Exceptions\BadRequestException;
use App\Exceptions\UnauthorizedException;
use App\Middleware\AuthMiddleware;
use App\User\User;
use DomainException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Psr7\Response;
use Throwable;
class AuthController
{
@ -36,24 +38,13 @@ class AuthController
password: $body['password'] ?? null,
),
);
} catch (BadRequestException $exception) {
return $this->jsonResponse(
new Response(400),
['error' => $exception->getMessage()],
400,
);
} catch (UnauthorizedException $exception) {
return $this->jsonResponse(
new Response(401),
['error' => $exception->getMessage()],
401,
);
} catch (Throwable $exception) {
return $this->errorResponse($exception);
}
$session = $this->createSession->execute($user);
$response = $this->jsonResponse(
new Response(200),
['user' => $this->buildUserPayload($user)],
200,
);
@ -98,14 +89,12 @@ class AuthController
if (! $user instanceof User) {
return $this->jsonResponse(
new Response(401),
['error' => 'unauthenticated'],
401,
);
}
return $this->jsonResponse(
new Response(200),
['user' => $this->buildUserPayload($user)],
200,
);
@ -120,16 +109,38 @@ class AuthController
}
private function jsonResponse(
ResponseInterface $response,
array $data,
int $status,
): ResponseInterface {
$response = $response->withStatus($status);
$response = new Response($status);
$response->getBody()->write(json_encode($data));
return $response->withHeader('Content-Type', 'application/json');
}
private function errorResponse(Throwable $exception): ResponseInterface
{
if ($exception instanceof BadRequestException) {
return $this->jsonResponse(
['error' => $exception->getMessage()],
400,
);
}
if ($exception instanceof UnauthorizedException) {
return $this->jsonResponse(
['error' => $exception->getMessage()],
401,
);
}
if ($exception instanceof DomainException) {
return $this->jsonResponse(
['error' => $exception->getMessage()],
409,
);
}
throw $exception;
}
private function parseBody(ServerRequestInterface $request): array
{
$contentType = $request->getHeaderLine('Content-Type');