I'm writing an AuthService and I don't know how should I show the output. I decided to throw an exception for errors and a simple array for successful messages. I want to know if it's okay or there is a better way.
Let's say we have a function that check's if the email has already exist in DB or not:
public function checkEmailExist(string $email)
{
$user = $this->getUserByEmail($email);
if ($user) {
throw new EmailAlreadyExistException();
}
return [
'message' => 'Ok',
];
}
And the exception class defined like this to prevent messing the logs:
use Exception;
use Symfony\Component\HttpFoundation\Response;
class EmailAlreadyExistException extends Exception
{
public function render()
{
return response()->json([
'message' => __('errors.general'),
'errors' => [
'email' => [__('errors.user.email_already_exists')],
],
], RESPONSE::HTTP_CONFLICT);
}
public function report()
{
}
}
And the controller:
public function check(CheckRequest $request)
{
return $this->authService->checkEmailExist(
email: $request->email,
);
}
To find out if a user with the entered email address already exists, you can use the
existsvalidation rule already present in the framework: https://laravel.com/docs/9.x/validation#rule-existsA validation error will then be displayed instead of an exception which is absolutely not meaningful to a user.
Then, if you want to catch validation errors to return formatted responses according to your API specifications, you can modify the exception handler of Laravel: https://laravel.com/docs/9.x/errors#rendering-exceptions