dsigh7478 2014-10-06 06: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.

  1. App::error(function(ModelNotFoundException $e)
  2. {
  3. return Response::json('', 404);
  4. });

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:

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

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

  • 写回答

2条回答 默认 最新

  • duande1985 2014-10-06 06: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:

    1. if (Request::format() == 'json')
    2. {
    3. //
    4. }

    (above is taken from the documentation)

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

    1. App::error(function(ModelNotFoundException $e)
    2. {
    3. if (Request::format() == 'json') {
    4. return Response::json('', 404);
    5. } else {
    6. return Response::view('404.html', [], 404);
    7. }
    8. });

    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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部