我在 API Laravel 專案中作業并嘗試處理“訊息”:“模型 ID 沒有查詢結果”和第 404 頁
我使用此功能,但不在 API 中發送任何內容,并且對 404 頁面沒有影響
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class Handler extends ExceptionHandler
{
public function render($request, Exception $e)
{
// "message": "No query results for model ID" in API
if ($e instanceof ModelNotFoundException) {
return response()->json(['error' => 'Data not found.']);
}
if($this->isHttpException($e))
{
switch ($e->getStatusCode())
{
// not found
case 404:
return redirect()->guest('home');
break;
// internal error
case '500':
return redirect()->guest('home');
break;
default:
return $this->renderHttpException($e);
break;
}
}
else
{
return parent::render($request, $e);
}
}
}
uj5u.com熱心網友回復:
使用 Throwable 而非例外
public function render($request, Throwable $e)
{
// "message": "No query results for model ID" in API
if ($e instanceof ModelNotFoundException) {
return response()->json(['error' => 'Data not found.']);
}
return parent::render($request, $e);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407937.html
標籤:
