<?php

namespace App\Exceptions;

use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of exception types with their corresponding custom log levels.
     *
     * @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
     */
    protected $levels = [
        //
    ];

    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<\Throwable>>
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->renderable(function (AuthenticationException $e) {
            return [
                'code' => 403,
                'message' => "未通过身份验证",
                'data'=>''
            ];
        });
    }
    public function render($request, Throwable $exception)
    {
        /**
         * Render an exception into an HTTP response.
         *
         * 替换渲染功能
         * Request::isMethod('post')                            请求方法为post
         * $exception instanceof MethodNotAllowedHttpException  $exception异常是MethodNotAllowedHttpException实例化的结果
         * 此方式针对访问不存在的方法GET方法无用,将继续渲染一个404的页面,因此在api.php路由最后定义了一个回退路由,针对GET方法的
         */
        // if (Request::isMethod('post') && $exception instanceof MethodNotAllowedHttpException) {
        if ($exception instanceof MethodNotAllowedHttpException) {
            return response()->json([
                'code' => 404,
                'msg' => '地址不存在',
                'data' => null
            ], 200
            );
        }

        return parent::render($request, $exception);
    }
}