Laravel 5 - 如何处理 MethodNotAllowedHttpException

Laravel 5 - How do I handle MethodNotAllowedHttpException

我在哪里可以在 Laravel 5+ 中捕捉到 MethodNotAllowedHttpException

在 Laravel 4 我能够在 start/global.php 做到这一点。

// Exceptions/Handler.php

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

public function render($request, \Exception $e)
{
    if ($e instanceof MethodNotAllowedHttpException) {
        // …
    }

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

Laravel 5.4中,我是这样做的:

文件位置:app/Exceptions/Handler.php

在文件顶部添加此代码:

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

并修改方法代码如下:

/**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof MethodNotAllowedHttpException) 
        {
            return response()->json( [
                                        'success' => 0,
                                        'message' => 'Method is not allowed for the requested route',
                                    ], 405 );
        }

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

别忘了包括:

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

使用此方法可用于任何版本的 laravel

if ($exception instanceof MethodNotAllowedHttpException) 
{
    return redirect()->route('yourWishedRoute');
}