laravel sanctum 错误自定义返回

laravel sanctum 错误自定义返回

现象

sanctum 认证失败会自动返回401或419 errercode,
前端认证逻辑这里会受到影响,所以希望可以自定义错误返回。

解决方法

根据

https://laravel.com/docs/9.x/errors#introduction

错误处理定义的handler内处理,这个类继承自框架的vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php

    public function render($request, Throwable $e)
    {
        if (method_exists($e, 'render') && $response = $e->render($request)) {
            return Router::toResponse($request, $response);
        }

        if ($e instanceof Responsable) {
            return $e->toResponse($request);
        }

        $e = $this->prepareException($this->mapException($e));

        if ($response = $this->renderViaCallbacks($request, $e)) {
            return $response;
        }

        return match (true) {
            $e instanceof HttpResponseException => $e->getResponse(),
            $e instanceof AuthenticationException => $this->unauthenticated($request, $e),
            $e instanceof ValidationException => $this->convertValidationExceptionToResponse($e, $request),
            default => $this->renderExceptionResponse($request, $e),
        };
    }

这里用到php8的match表达式,顺便学习一下

https://www.php.net/manual/en/control-structures.match.php

可以看到会调用到unauthenticated这个方法,方法是protected的,所以可以在项目里继承自这个handler的类里面覆写这个方法

    protected function unauthenticated($request, AuthenticationException $exception) {
        return response()->json(['code' => 403, 'message' => '未授权']);
    }

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注