2016-04-02 14 views
4

Laravel 5とDingoを使用してAPIを構築しています。ルートが定義されていないリクエストをどのようにキャッチするのですか?私のAPIは、特別な形式のJSONレスポンスで常に応答したいと思っています。Laravel 5 API with Dingo

たとえば、私にルートがある場合: $ api-> get( 'somepage'、 'mycontroller @ mymethod');

経路が定義されていないと仮定して、誰かが同じURIへの投稿を作成するケースをどうすれば処理できますか?

何が起こっているのかは、LaravelがMethodNotAllowedHttpExceptionをスローしていることです。

Route::any('/{all}', function ($all) 
    { 
     $errorResponse = [ 
      'Message' => 'Error', 
      'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ] 
     ]; 
     return Response::json($errorResponse, 400);  //400 = Bad Request 
    })->where(['all' => '.*']); 

が、私はスローMethodNotAllowedHttpExceptionを得続ける:

私はこれを試してみました。

これを行う方法はありますか?ミドルウェアを使う?すべてのルートのキャッチのいくつかの他の形式ですか?

EDIT:

は、それは効果がなかったHandler.php

public function render($request, Exception $e) 
{ 
    dd($e); 
    if ($e instanceof MethodNotAllowedHttpException) { 
     $errorResponse = [ 
      'Message' => 'Error', 
      'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ] 
     ]; 
     return Response::json($errorResponse, 400); 
    } 
    return parent::render($request, $e);   
} 

\アプリケーション\例外にこれを追加しようとしました。私はdump-autoloadとそのすべてをやった。私はdd($ e)を加えても何の効果もありませんでした。これは私にとって奇妙に思える。

EDIT - SOLUTION

はそれを考え出しました。ジェームズの答えが私に正しい方向に考えさせたが、何が起こっていたのはディンゴがエラー処理を無効にしていたことだ。このエラーに対するレスポンスをカスタマイズするには、app \ Providers \ AppServiceProvider.phpを変更する必要があります。それは私が正しい方向に向かっ得たので、このようなブート機能(デフォルトではその空)

ジェームズの答えを受け入れる
public function boot() 
{ 
    app('Dingo\Api\Exception\Handler')->register(function (MethodNotAllowedHttpException $exception) { 
     $errorResponse = [ 
      'Message' => 'Error', 
      'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ] 
     ]; 
     return Response::make($errorResponse, 400); 
    }); 
} 

を行います。

・ホープこれは誰かに役立ちます:)これはMethodNotAllowedHttpExceptionのインスタンスである場合は、例外をキャッチしてチェックすることにより、app/Exceptions/Handler.phpの内側にこれを行うことができますぐふ

答えて

3

....私の夜のより良い部分を取り上げました。

この場合、論理を実行してカスタムエラー応答を返すことができます。

NotFoundHttpExceptionのインスタンスをキャッチする場合は、同じ場所でチェックをカスタマイズすることもできます。

// app/Exceptions/Handler.php 

public function render($request, Exception $e) 
    { 
     if ($e instanceof MethodNotAllowedHttpException) { 
      $errorResponse = [ 
       'Message' => 'Error', 
       'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ] 
      ]; 
      return Response::json($errorResponse, 400); 
     } 

     if($e instanceof NotFoundHttpException) 
     { 
      $errorResponse = [ 
       'Message' => 'Error', 
       'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ] 
      ]; 
      return Response::json($errorResponse, 400); 
     } 

     return parent::render($request, $e); 
    } 
関連する問題