Better Errors

This commit is contained in:
2024-07-23 01:12:05 +02:00
parent 30849019af
commit 85d20e034a
18 changed files with 567 additions and 390 deletions
+15 -24
View File
@@ -4,6 +4,7 @@ namespace Api\Post;
use Exception;
use Khofmann\Api\Api;
use Khofmann\ApiError\ApiError;
use Khofmann\Input\Input;
use Khofmann\Models\Post\Post as MPost;
use Khofmann\Models\User\User;
@@ -12,40 +13,29 @@ use Khofmann\Response\Response;
class Post extends Api
{
public function post(): void
{
$content = Input::patch("content");
$self = User::getByToken(Request::token());
try {
Response::json(MPost::create($self, $content));
} catch (Exception $err) {
switch ($err->getMessage()) {
default:
throw $err;
}
}
}
public function patch($id): void
{
// Fetch all inputs.
$content = Input::patch("content");
// Fetch authed user.
$self = User::getByToken(Request::token());
$post = MPost::getByID($id);
if (!$self->getIsAdmin() && $post->getUser()->getID() !== $self->getID()) throw new Exception("Not Authorized", 401);
try {
Response::json(MPost::getByID($id)->update($content));
// Try fetch the post in question, 404 if not found.
$post = MPost::getByID($id);
// Throw 400 if we aren't admin but trying to edit another users post.
if (!$self->getIsAdmin() && $post->getUser()->getID() !== $self->getID()) throw ApiError::unauthorized("Not allowed");
// Try update.
Response::json($post->update($content));
} catch (Exception $err) {
switch ($err->getMessage()) {
case "NotFound":
throw new Exception("Post not found", 404);
case "FailedContent":
throw new Exception("Failed to update content", 500);
throw ApiError::notFound("post");
default:
// Due to how the failed field is handled, it's ApiError is inside the models update
throw $err;
}
}
@@ -53,12 +43,13 @@ class Post extends Api
public function delete($id): void
{
// Try delete, 404 if post was not found.
try {
Response::json(MPost::getByID($id)->delete());
} catch (Exception $err) {
switch ($err->getMessage()) {
case "NotFound":
throw new Exception("Post not found", 404);
throw ApiError::notFound("post");
default:
throw $err;
}