feat: update error handling logic

This commit is contained in:
Miguel Nogueira 2025-04-13 22:18:14 +01:00
parent 46c6dd6e58
commit 54c2c8e897
4 changed files with 29 additions and 5 deletions

View File

@ -13,6 +13,8 @@ $app->addBodyParsingMiddleware();
$app->get('/', [HomeFrontController::class, 'home']);
$app->get('/tasks', [TaskController::class, 'getTasks']);
$app->post('/tasks', [TaskController::class, 'addTask']);
$app->run();

View File

@ -102,7 +102,9 @@ class TaskController
->setStartDt($params['tasks']['start'])
->setEndDt($params['tasks']['end']);
if (!$this->repository->create($task))
$createdTask = $this->repository->create($task);
if ($createdTask == 0)
{
$this->builder->setError()
->setErrorMessage('An unexpected error has occurred whilst trying to perform this operation.')
@ -116,9 +118,20 @@ class TaskController
$createdResponse = $response->withStatus(201)->withHeader('Content-Type', 'application/json');
$this->builder->setOptionalMessage('Task created.')
->setPayload($task->persist());
->setPayload($task->setId($createdTask)->persist());
$createdResponse->getBody()->write($this->builder->build());
return $createdResponse;
}
public function getTasks(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
{
$tasks = $this->repository->readAll();
$payload['tasks'] = $tasks;
$this->builder->setPayload($payload)->setOptionalMessage('Listing all tasks: ');
$response->getBody()->write($this->builder->build());
return $response;
}
}

View File

@ -6,7 +6,13 @@ use Models\Task;
interface TaskDao
{
public function create(Task $task): bool;
/**
* Inserts the specified task.
*
* @param Task $task The task to persist.
* @return int The new task's ID, or 0 if the operation was unsucessful
*/
public function create(Task $task): int;
/**
* Returns an array of Tasks

View File

@ -19,7 +19,7 @@ class TaskRepository implements TaskDao
$this->conn = $connection->getConnection();
}
public function create(Task $task): bool
public function create(Task $task): int
{
$data = $task->persist();
$stmt = $this->conn->prepare(
@ -35,8 +35,11 @@ class TaskRepository implements TaskDao
$stmt->bindParam(7, $data['end']);
$stmt->bindParam(8, $data['status_id']);
if ($stmt->execute()) {
return (int) $this->conn->lastInsertId();
}
return $stmt->execute();
return 0;
}
public function readAll(): array