【问题标题】:Laravel route model binding 500 errorLaravel 路由模型绑定 500 错误
【发布时间】:2018-04-05 20:38:53
【问题描述】:

我有这样的路线

Route::get('/articles/{article}', 'ArticleController@show');

一切正常,但如果您将 mydomain.com/articles/non-existent 放在文章名称不存在的地方,我会收到内部错误。

为什么不返回 404 或者我如何让它返回 404 或者我如何处理内部错误以显示页面而不会弄乱 404 错误处理?

我目前在我的 Exceptions/Handler.php 中有这个

public function render($request, Exception $exception)
{
    if ($this->isHttpException($exception)) {
        return response()->view('errors.404', [], 404);
    }else{
        return response()->view('errors.500', [], 500);
    }
}

这总是返回 500 页面,即使它只是一个正常的 404 错误。

感谢您的帮助!

【问题讨论】:

    标签: laravel error-handling routing laravel-5.3


    【解决方案1】:

    尝试找出它是什么类型的异常,因为 isHttpException 非常通用。同样在你的情况下,它甚至不是 NotFoundHttpException,因为它没有返回 404。如果你得到 500,那肯定是因为 errorException。

        //This will let you know if your dealing with 404 or not
    
        if($exception instanceof NotFoundHttpException)
        {
            return response()->view('front.missing', [], 404);
        }
        else 
        {
    
          return response()->view('errors.500', [], 500);
    
        }
    

    【讨论】:

    • 感谢您的回复。如果有路由,则路由模型绑定有效。如果路由不存在,它会显示 500 错误。我正在获取自定义错误页面,但即使在不使用路由模型绑定的页面上也会显示 500 错误页面,并且应该只返回 404 错误页面。
    【解决方案2】:

    你应该在你的控制器上抛出一个异常。这样就可以看到404页面了。

    $article = Article::find(article_id); // or with slug
    If(!$article){
        throw new NotFoundHttpException;
    }
    

    【讨论】:

    • 感谢您的回复。这应该可以,但似乎 Exception/Handler.php 在它到达控制器之前运行。我仍然得到我创建的自定义 500 页面,而不是 404
    猜你喜欢
    • 2017-06-22
    • 2020-12-20
    • 2021-05-24
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 2018-12-17
    • 2015-07-12
    相关资源
    最近更新 更多