Laravel 5 - How do I handle MethodNotAllowedHttpException

安稳与你 提交于 2019-12-18 04:38:07

问题


Where can I catch a MethodNotAllowedHttpException in Laravel 5+?

In Laravel 4 I was able to do this in start/global.php.


回答1:


// Exceptions/Handler.php

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

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

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



回答2:


In Laravel 5.4, I did it like this:

File location: app/Exceptions/Handler.php

Add this code at the top of the file:

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

And modify the method code as belows:

/**
     * 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);
    }



回答3:


Don't forget to include:

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

use this method it will work on any version of laravel

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


来源:https://stackoverflow.com/questions/30276325/laravel-5-how-do-i-handle-methodnotallowedhttpexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!