需求:未授权状态下总是返回{“message“:“Unauthenticated.“},想自定义

解决方案:在app/Exceptions/Handler.php中添加render方法(即继承父类的render方法并自定义)

 

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Routing\Router;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Validation\ValidationException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    /**
     * 重写异常
     * @param \Illuminate\Http\Request $request
     * @param Throwable $e
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     * @throws \ReflectionException
     */
    public function render($request, Throwable $e)
    {

        if (method_exists($e, 'render') && $response = $e->render($request)) {

            return Router::toResponse($request, $response);
        } elseif ($e instanceof Responsable) {

            return $e->toResponse($request);
        }

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

        foreach ($this->renderCallbacks as $renderCallback) {
            if (is_a($e, $this->firstClosureParameterType($renderCallback))) {
                $response = $renderCallback($e, $request);

                if (! is_null($response)) {
                    return $response;
                }
            }
        }

        if ($e instanceof HttpResponseException) {

            return $e->getResponse();
        } elseif ($e instanceof AuthenticationException) {
            
            return apiResponse(403,$e->getMessage());
            // return $this->unauthenticated($request, $e);
        } elseif ($e instanceof ValidationException) {

            return $this->convertValidationExceptionToResponse($e, $request);
        }

        return apiResponse(500, $e->getMessage());
//        return $request->expectsJson()
//            ? $this->prepareJsonResponse($request, $e)
//            : $this->prepareResponse($request, $e);
    }
}

 

修改后,响应信息:

{
    "code": 403, 
    "message": "未授权", 
    "data": [ ]
}
{
    "code": "500", 
    "message": "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ...", 
    "data": [ ]
}