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,
);
}