1

私は例外処理を担当するサービスレイヤーを持っています。例外を処理し、サービスレイヤーから応答オブジェクトを返す

サービスレイヤで例外を処理する必要があり、ビューに適切な例外メッセージを渡すにはどうすればよいですか。

class App_Service_Feed { 
    function create() { 
    //... 
    try { 
     $feed->getMapper->insert(); 
    } catch (Zend_Db_Statement_Exception $e) { 
     //what do I return here?   
    } catch (Exception $e) { 
     //what do I return here? 
    } 
    } 
} 

私はいくつかの説明の応答オブジェクトを返すことを考えているので、私のコントローラではこれを操作します。

class App_Controller { 
    //... 
    $response = $service->create(); 
    if($response->status) { 

    } 
} 

代わりに、私は...コントローラでの例外を処理するかどうかを

+0

質問の素敵な説明は+1。 – amod

答えて

1
それをキャッチするためにZendのフロントコントローラの例外がスローされます

ジェイソン・ボーンの方法(ええ)よりもさらに良い:

class App_Service_Feed { 
    function create() { 
    //... 
    try { 
     $feed->getMapper->insert(); 
    } 
    catch (Zend_Db_Statement_Exception $e) 
    { 
     throw new App_Service_Feed_Exception("Your own message", NULL, $e);  
    } 
    catch (Exception $e) 
    { 
     throw new App_Service_Feed_Exception("Your other message", NULL, $e); 
    } 
    } 
} 

なぜ、これは良いですか?

  • 独自のExceptionクラス(Zend_Exceptionを拡張)を使用しています。したがって、例外がスローされた場所をすぐに見ることができ、独自の追加チェックなどを組み込むことができます。
  • 最後の例外を渡してExceptionに関する履歴情報(トレース)を追加します。

例外を実装する最良の方法は、Exceptionクラスを拡張する階層を持つことです。

App_Exception extends Zend_Exception 
App_Service_Exception extends App_Exception 
App_Service_Feed_Exception extends App_Service_Exception 

すべてのフォルダにはException.phpが含まれています。こうすることで、必要に応じてあらゆるレベルで例外をキャッチして元に戻すことができます。

1

を思ったんだけど、あなたがする必要があるのは、後者の

class App_Service_Feed { 
    function create() { 
    //... 
    try { 
     $feed->getMapper->insert(); 
    } catch (Zend_Db_Statement_Exception $e) { 
     throw new Zend_Exception("my own message");  
    } catch (Exception $e) { 
     throw new Zend_Exception("my different message"); 
    } 
    } 
} 
0

あなたは私が例外処理を行うために使用したときに、私は通常、それに続く、このアプローチに従うことができます。

class App_Service_Feed { 


function create() throws CustomException, OtherCustomException { 
    //... 
    try { 
     $feed->getMapper->insert(); 
    } catch (Zend_Db_Statement_Exception $e) { 
     //you can throw ur custom exception here. 
     //By doing so you can increase its functionality and understand what is the problem 
     throw new CustomException();  
    } catch (Exception $e) { 
     //here u can check some general exception like NullPointer, IOException etc(related 
     //to ur case) using instanceof. 
     throw new OtherCustomException 

    } 
    } 
} 

は、今すぐあなたのコントローラで、あなたがこの例外を処理し、いくつかのメッセージを表示する必要があります -

class App_Controller { 
    //... 
    App_Service_Feed obj = new App_Service_Feed(); 
    try{ 
    obj.create() 
    }catch(CustomException c) 
    { 
    //display message 
    }catch(OtherCustomException o) 
    { 
     //display other message 
    } 
    } 
}