Better Errors
This commit is contained in:
@@ -4,6 +4,7 @@ namespace Api\Login;
|
||||
|
||||
use Exception;
|
||||
use Khofmann\Api\Api;
|
||||
use Khofmann\ApiError\ApiError;
|
||||
use Khofmann\Input\Input;
|
||||
use Khofmann\Response\Response;
|
||||
use Khofmann\Models\User\User;
|
||||
@@ -12,21 +13,27 @@ class Login extends Api
|
||||
{
|
||||
public function post(): void
|
||||
{
|
||||
// Fetch all required inputs.
|
||||
// Throw 400 error if a required one is missing.
|
||||
$missing = [];
|
||||
$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($email)) array_push($missing, "email");
|
||||
if (empty($password)) array_push($missing, "password");
|
||||
if (count($missing) > 0) throw ApiError::missingField($missing);
|
||||
|
||||
// Try and log in user.
|
||||
// Throw errors according to situation.
|
||||
try {
|
||||
Response::json(User::logIn($email, $password));
|
||||
} catch (Exception $err) {
|
||||
switch ($err->getMessage()) {
|
||||
case "Failed":
|
||||
throw new Exception("Login failed", 500);
|
||||
throw ApiError::failed("Login failed");
|
||||
case "NotFound":
|
||||
throw new Exception("User not found", 404);
|
||||
throw ApiError::notFound("user");
|
||||
case "Invalid":
|
||||
throw new Exception("Invalid username or password", 401);
|
||||
throw ApiError::unauthorized("Invalid username or password");
|
||||
default:
|
||||
throw $err;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user