Laravel 5 - 如何处理MethodNotAllowedHttpException

时间:2015-05-16 13:33:47

标签: php laravel error-handling exception-handling laravel-5

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

在Laravel 4中,我能够在start/global.php中完成此任务。

2 个答案:

答案 0 :(得分:25)

// Exceptions/Handler.php

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

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

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

答案 1 :(得分:12)

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