Laravel - 无法处理MethodNotAllowedHttpException

时间:2013-12-06 14:59:20

标签: php laravel exception exception-handling laravel-4

我正在尝试自定义MethodNotAllowedHttpException错误,但我没有到达任何地方。

#app/start/global.php

App::error(function(MethodNotAllowedHttpException $exception)
{
    Response::make("Test...", 503); 
});

它只显示一个空白/空白页面。

但是,如果我将MethodNotAllowedHttpException替换为Exception则可行。但这显示出很多错误,我只想要这种类型。

思想?

1 个答案:

答案 0 :(得分:1)

在Laravel 5中,异常应该在app / Exceptions / Handler.php中处理,如下所示:

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $e
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $e)
{
    if ($e instanceof ModelNotFoundException) {
        $e = new NotFoundHttpException($e->getMessage(), $e);
    }

    if ($e instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException) {
        return abort('503');
    }

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

但是,我不会将503用于这些类型的错误,因为它不符合HTTP规范。如果该路径不允许该方法,那么405将更合适。

然后,您可以在resources / views / errors / 405.blade.php中创建一个视图,以向用户显示一些不错的内容。