dsigh7478 2014-10-06 14:19
浏览 163
已采纳

Laravel自定义ModelNotFoundException处理每个路由组

I have two route groups in my Laravel application, one for an API and one for the website itself. I've added the following code in global.php for error handling of my API.

App::error(function(ModelNotFoundException $e)
{
   return Response::json('', 404);
});

But not this obviously also has effect on my normal website, where I want to return a normal view when the ModelNotFoundException occurs. Like so:

App::error(function(ModelNotFoundException $e)
{
   return Response::view('404.html', [], 404);
});

How can I setup different error handlers for different route groups?

  • 写回答

2条回答 默认 最新

  • duande1985 2014-10-06 14:49
    关注

    I think you shouldn't care what part of the site that threw the error, but instead respond with whatever format the client requested. In general this is set in the Accepts header of the request and can be accessed in Laravel by:

    if (Request::format() == 'json')
    {
        //
    }
    

    (above is taken from the documentation)

    In your case, this would turn your error handling function to this:

    App::error(function(ModelNotFoundException $e)
    {
       if (Request::format() == 'json') {
           return Response::json('', 404);
       } else {
           return Response::view('404.html', [], 404);
       }
    });
    

    This automatically covers you if, for instance, you add an non-API AJAX request to the main portion of your website (for whatever reason) that could potentially trigger a ModelNotFoundException. As long as your client sends the appropriate request headers, you're good.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题