2017-04-27 84 views
3

我想显示API和网站的不同响应。在api响应中,我想显示json响应404和500,主要针对路由的异常类型。Laravel 404和500的API和网站中的不同响应(JSON和网页)?

如果用户尝试请求找不到路由和路由,我想在网站的API和网页的json响应中显示响应。

我知道,并尝试将代码放到app/Exceptions/Handler.php

public function render($request, Exception $exception) 
{ 
    if ($exception instanceof NotFoundHttpException) { 
     if ($request->expectsJson()) { 
      return response()->json(['error' => 'Not Found'], 404); 
     } 
     return response()->view('404', [], 404); 
    } 
    return parent::render($request, $exception); 
} 

https://laravel.com/docs/5.4/errors#http-exceptions

,但没有任何人可以帮助我,我怎么可以设置错误页面不同的反应。

回答

2

预计公司JSON约为头,我不喜欢这样的解决方案API错误是诚实的,你可以通过例如浏览器访问它。我的解决方案是通过url路由进行过滤的大部分时间,因为它通常以"api/..."开头,可以像$request->is('api/*')这样完成。

如果你有一个/ api路由,那么这将工作,否则更改请求是可以完成调用。

public function render($request, Exception $exception) 
{ 
    if ($exception instanceof NotFoundHttpException) { 
     if ($request->is('api/*')) { 
      return response()->json(['error' => 'Not Found'], 404); 
     } 
     return response()->view('404', [], 404); 
    } 
    return parent::render($request, $exception); 
} 
+0

这适用于我,还加入'''使用Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException;'''Thankyou –

-1

try this.

public function render($request, Exception $exception) 
    { 
     if ($request->ajax()) { 
      return \Response::json([ 
       'success' => false, 
       'message' => $exception->getMessage(), 
      ], $exception->getCode()); 
     } else { 
      return parent::render($request, $exception); 
     } 
    } 
+0

“X-Requested-With”:“XMLHttpReques”需要在标题中添加,否则laravel请求不会检测为ajex调用,为什么返回一个页面。 –

0

我使用Laravel 5.5.28,和我在app/Exceptions/Handler.php

public function render($request, Exception $exception) 
{ 
    // Give detailed stacktrace error info if APP_DEBUG is true in the .env 
    if ($request->wantsJson()) { 
     // Return reasonable response if trying to, for instance, delete nonexistent resource id. 
     if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) { 
     return response()->json(['data' => 'Resource not found'], 404); 
     } 
     if ($_ENV['APP_DEBUG'] == 'false') { 
     return response()->json(['error' => 'Unknown error'], 400); 
     } 
    } 
    return parent::render($request, $exception); 
} 

加入这个这个期望你的API调用将具有关键Accept和值application/json头。

然后一个不存在的网络路由返回预期

对不起,您要找的页面无法找到

和一个不存在的API资源返回一个JSON 404的有效载荷。

找到info here

你可以结合这个与寻找NotFoundHttpException的实例来捕获500的答案。然而,我想象,堆栈跟踪将是首选。