Laravel 5 - 如何处理 MethodNotAllowedHttpException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30276325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:34:23  来源:igfitidea点击:

Laravel 5 - How do I handle MethodNotAllowedHttpException

phplaravelerror-handlingexception-handlinglaravel-5

提问by Salal Aslam

Where can I catch a MethodNotAllowedHttpExceptionin Laravel 5+?

我在哪里可以MethodNotAllowedHttpException在 Laravel 5+ 中找到一个?

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

在 Laravel 4 中,我能够在start/global.php.

回答by Limon Monte

// Exceptions/Handler.php

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

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

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

回答by Rahul Gupta

In Laravel 5.4, I did it like this:

Laravel 5.4,我是这样做的:

File location: app/Exceptions/Handler.php

文件位置: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);
    }

回答by Azeem Ghafoor

Don't forget to include:

不要忘记包括:

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

use this method it will work on any version of laravel

使用这种方法它可以在任何版本的 Laravel 上工作

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