Better Errors
This commit is contained in:
@@ -4,6 +4,7 @@ namespace Api\Register;
|
||||
|
||||
use Exception;
|
||||
use Khofmann\Api\Api;
|
||||
use Khofmann\ApiError\ApiError;
|
||||
use Khofmann\Input\Input;
|
||||
use Khofmann\Response\Response;
|
||||
use Khofmann\Models\User\User;
|
||||
@@ -12,19 +13,26 @@ class Register extends Api
|
||||
{
|
||||
public function post(): void
|
||||
{
|
||||
// Fetch all required inputs.
|
||||
// Throw 400 error if a required one is missing.
|
||||
$missing = [];
|
||||
$username = Input::post("username");
|
||||
if (empty($username)) throw new Exception("Missing username", 400);
|
||||
$email = Input::post("email");
|
||||
if (empty($email)) throw new Exception("Missing email", 400);
|
||||
$password = Input::post("password");
|
||||
if (empty($password)) throw new Exception("Missing password", 400);
|
||||
if (empty($username)) array_push($missing, "username");
|
||||
if (empty($email)) array_push($missing, "email");
|
||||
if (empty($password)) array_push($missing, "password");
|
||||
if (count($missing) > 0) throw ApiError::missingField($missing);
|
||||
|
||||
// Try and create a new user, 400 if duplicate.
|
||||
try {
|
||||
Response::json(User::create($username, $email, $password));
|
||||
} catch (Exception $err) {
|
||||
switch ($err->getMessage()) {
|
||||
case "NotFound":
|
||||
throw ApiError::failed("Failed to create user");
|
||||
case "Duplicate":
|
||||
throw new Exception("A user with this username or email already exists", 400);
|
||||
throw ApiError::duplicate("user");
|
||||
default:
|
||||
throw $err;
|
||||
}
|
||||
@@ -33,15 +41,18 @@ class Register extends Api
|
||||
|
||||
public function patch(): void
|
||||
{
|
||||
// Fetch all required inputs.
|
||||
// Throw 400 error if a required one is missing.
|
||||
$code = Input::post("code");
|
||||
if (empty($code)) throw new Exception("Missing code", 400);
|
||||
if (empty($code)) throw ApiError::missingField(["code"]);
|
||||
|
||||
// Try and confirm user, 404 if user not found.
|
||||
try {
|
||||
Response::json(User::confirm($code));
|
||||
} catch (Exception $err) {
|
||||
switch ($err->getMessage()) {
|
||||
case "NotFound":
|
||||
throw new Exception("User not found", 404);
|
||||
throw ApiError::notFound("user");
|
||||
default:
|
||||
throw $err;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user