What should I do with error/successful messages in Laravel service classes

458 Views Asked by At

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

There are 1 best solutions below

3
Jedupont On

To find out if a user with the entered email address already exists, you can use the exists validation rule already present in the framework: https://laravel.com/docs/9.x/validation#rule-exists

A 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

use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;

///

$this->renderable(function (ValidationException $e, $request) {
    return response()->json([
        'message' => 'validation_rule_failed',
        'errors' => $e->errors(),
    ], Response::HTTP_UNPROCESSABLE_ENTITY);
});