2013-07-11 35 views
2

我有一個Grails應用程序,我想知道從我的服務層向我的控制器傳遞錯誤和消息的最佳方式。例如,假設我點擊了我的應用程序中的一個鏈接,該鏈接調用服務並將我帶到新頁面。在我的應用程序,新的一頁,我想看到像這樣的郵件列表:在Grails服務中處理錯誤和消息的最佳方法

Information: 10 files processed successfully. 

Warning: FileA is missing CreationDate 

Error: FileB failed processing 
Error: FileC failed processing 
Error: FileD failed processing 

我知道,我可以創造像「ServiceReturnObject」自定義對象具有類似性質:

def data 
def errors 
def warnings 
def information 

並讓我所有的服務都返回這個對象。

我也知道我可以使用異常,但我不確定這是否是具有多個異常和多種異常類型的正確解決方案。

這裏的最佳做法是什麼?示例會很有幫助,謝謝。

回答

1

要返回錯誤,我會創建一個自定義異常類,並使用它來包裝服務可以生成的所有其他錯誤。這樣,你只需要捕捉有限的例外。如果你有一個以上的控制器方法/關閉,需要返回錯誤,我會因素這樣的代碼:

首先,創建您的異常類,並把它放在src/java的在正確的命名空間:

class MyException extends Exception { 
    protected String code; // you could make this an int if you want 
    public String getCode() { return code; } 

    public MyException(String code, String message) { 
     super(message); 
     this.code = code; 
    } 
} 
現在

,在你的控制器,創建一個錯誤處理方法,並在其包所有來電

class MyController { 
    def myService; 

    def executeSafely(Closure c) { 
     Map resp = [:] 
     try { 
      resp.data = c(); 
     } 
     catch(MyException myEx) { 
      resp.error = myEx.getMessage(); 
      resp.code = myEx.getCode(); 
     } 
     catch(Exception ex) { 
      resp.error = 'Unexpected error: ' + ex.getMessage(); 
      resp.code = 'foo'; 
     } 

     return resp; 
    } 


    def action1 = { 
     def resp = executeSafely { 
      myService.doSomething(params); 
     } 

     render resp as JSON; 
    } 

    def action2 = { 
     def resp = executeSafely { 
      myService.doSomethingElse(params); 
     } 

     render resp as JSON; 
    } 
} 

或者,你可以有executeSafely轉換成JSON響應,並只呈現直接。

+0

然後你是否只從服務中拋出MyException? –

相關問題