2016-11-03 8 views
1

私はLaravel 5.3を使用しています。ユーザーが特定のIDを要求するAPIはほとんどありません。 idが存在しない場合の例URLが
example.com/api/event/{id}/subscribeLaravel 5 - 存在しないオブジェクトを要求するAPIのグローバル例外ハンドラ

通常イベントをサブスクライブするためにイベント場合

だから私はチェックを追加し は、Laravelは「非オブジェクトのプロパティを取得しようとすると、」エラーメッセージで応答500を返します。モデル「ID」のIDが渡されたすべてのコントローラには以下のような存在である:

$event = Event::find($id) 
if ($event) { 
    // return json data 
} 
else { 
    return response()->json([ 
     'status' => 'object not found' 
    ], 404); 
} 

私の質問は、オブジェクトが要求されたかどうかを確認するために、グローバルにこれを処理するために任意のより良い解決策は存在しないのですか?私の現在の解決策はここにありますが、より良いものがあるはずです。

このコードを私のapp/Exception/Handler.phpに追加すると、すべてのapiリクエストの存在しないオブジェクトは特定のjsonメッセージで404を返します。したがって、APIコンシューマはオブジェクトIDが有効でないことを認識します。

public function render($request, Exception $exception) 
{ 
    // global exception handler if api request for non existing object id 
    if ($request->wantsJson() && $exception->getMessage() == 'Trying to get property of non-object') { 
     return response()->json([ 
      'status' => 'object requested not found' 
     ], 404); 
    } 

    return parent::render($request, $exception); 
} 

ありがとうございます!

答えて

4

あなたにApp\Exceptions\Handlerクラスのrender()機能を使用することができます。

public function render($request, Exception $exception) 
{ 
    if ($request->wantsJson() && $exception instanceof ModelNotFoundException) { 
     return response()->json(['status' => 'object requested not found'], 404); 
    } 

    return parent::render($request, $exception); 
} 

、次のコードを追加することを忘れないでください:

use Illuminate\Database\Eloquent\ModelNotFoundException; 

Docs

+0

'Illuminate \ Database \ Eloquent \ ModelNotFoundException;を使用してください。ありがとう。また、 'wantsJson()'を使うコードを少し変更します – xmhafiz

2

は、私の知る限り、それはそのIDのために何を見つけることができなかった場合、それはModelNotFoundExceptionを投げるよ、覚えて

$event = Event::findOrFail($id) 

にご

$event = Event::find($id) 

を変更してみてください。 app/Exceptions/Handler.phpに移動し、レンダリングメソッド内で例外をキャッチして処理します。

編集:

if ($e instanceof HttpResponseException) { 
      return $e->getResponse(); 
     } elseif ($e instanceof ModelNotFoundException) { 
      $e = new NotFoundHttpException($e->getMessage(), $e); 
     } elseif ($e instanceof AuthenticationException) { 
      return $this->unauthenticated($request, $e); 
     } elseif ($e instanceof AuthorizationException) { 
      $e = new HttpException(403, $e->getMessage()); 
     } elseif ($e instanceof ValidationException && $e->getResponse()) { 
      return $e->getResponse(); 
     } 

をあなたは親がそれはModelNotFoundException例外を取得する場合の方法はNotFoundHttpExceptionを発射レンダリングすることがわかります。私はあなたの要件に合わせて上書きすることができると思います。

+0

'findOrFail'が良いのですが、それはNotFoundHttpExceptionとIを返すに上記のあなたの条件を使用しているときや 'if($ e instanceof NotFoundHttpException)を使ってチェックできないときにもチェックできます。ありがとう – xmhafiz

+0

@ h44f33z 'findOrFail'は' ModelNotFoundException 'を返しますが、親レンダリングメソッドは' NotFoundHttpException 'を起動します。要件に合わせて変更することができます。 – shoieb0101

+0

ですが、if($ e instanceof ModelNotFoundException)も一致しません。 – xmhafiz

関連する問題