2017-04-27 83 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的答案。然而,我想象,堆棧跟蹤將是首選。