我应该如何处理 Laravel 服务类中的错误/成功消息

问题描述 投票:0回答:1

我正在编写一个 AuthService,但我不知道应该如何显示输出。我决定针对错误抛出异常,并针对成功消息抛出一个简单的数组。我想知道是否可以或者有更好的方法。

假设我们有一个函数可以检查电子邮件是否已存在于数据库中:

    public function checkEmailExist(string $email)
    {
        $user = $this->getUserByEmail($email);

        if ($user) {
            throw new EmailAlreadyExistException();
        }

        return [
            'message' => 'Ok',
        ];
    }

并且这样定义异常类以防止弄乱日志:

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()
    {
    }
}

控制器:

    public function check(CheckRequest $request)
    {
        return $this->authService->checkEmailExist(
            email: $request->email,
        );
    }
laravel oop design-patterns code-cleanup
1个回答
0
投票

要查明输入电子邮件地址的用户是否已存在,您可以使用框架中已有的

exists
验证规则:https://laravel.com/docs/9.x/validation#rule-exists

然后将显示验证错误,而不是异常,这对用户来说绝对没有意义。

然后,如果你想捕获验证错误以根据你的 API 规范返回格式化响应,你可以修改 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);
});
© www.soinside.com 2019 - 2024. All rights reserved.