2012-07-18 37 views
4

我正在爲我們的客戶開發RESTful API。
如果發生錯誤,我即將顯示錯誤信息。
錯誤信息協議如下所示。如何在使用java開發RESTful API時控制異常?

{ 
    "status": "failure", 
    "error": { 
     "message": "", 
     "type": "", 
     "code": 0000 
    } 
} 

在編程水平,如何控制好例外?
現在我已經制定了延伸Exception類的自定義異常類。 (不是RuntimeException)
這種方法好不好?使用RuntimeExcepion更好嗎?
我的自定義異常類是...

public class APIException extends Exception { 
    public enum Code {  
     // duplicated exceptions 
     ALREADY_REGISTERED(1001), 

     // size exceptions 
     OVER_KEYWORD_LIMIT(2001), 
     OVER_CATEGORY_LIMIT(2002), 
     TOO_SHORT_CONTENTS_LENGTH(2003), 
     TOO_SHORT_TITLE_LENGTH(2004), 

     // database exceptions 
     DB_ERROR(3001), 

     // unregistered exceptions 
     UNREGISTERED_NAME(4001), 

     // missing information exceptions 
     MISSING_PARAMETER(5001), 

     // invalid information exceptions 
     INVALID_PARAMETER(6001), 
     INVALID_URL_PATTERN(6002); 

     private final Integer value; 
     private Code(Integer value) { 
      this.value = value; 
     } 
     public Integer getType() { 
      return value; 
     } 
    } 

    private final Code code; 

    public APIException(Code code) { 
     this.code = code; 
    } 
    public APIException(Code code, Throwable cause) { 
     super(cause); 
     this.code = code; 
    } 
    public APIException(Code code, String msg, Throwable cause) { 
     super(msg, cause); 
     this.code = code; 
    } 
    public APIException(Code code, String msg) { 
     super(msg); 
     this.code = code; 
    } 

    public Code getCode() { 
     return code; 
    } 
} 

而且使用API​​Exception類這樣的...

public void delete(int idx) throws APIException { 
    try { 
     Product product = productDao.findByIdx(idx); 
     if (product.getCount() > 0) { 
      throw new APIException(Code.ALREADY_REGISTERED, 
        "Already registered product."); 
     } 
     productDao.delete(idx); 
    } catch (Exception e) { 
     throw new APIException(Code.DB_ERROR, 
       "Cannot delete product. " + e.getMessage()); 
    } 
} 

哪個是更好的做定製的異常類,或使用存在異常喜歡拋出:IllegalArgumentException ..
如果使自定義異常類更好,我應該在Exception或RuntimeException中擴展什麼?
請推薦我喜歡我的情況的好例子。
在此先感謝。

+0

這似乎從一個問題過渡到另一種,考慮修改。要回答第二部分,最好使用自己的自定義異常。只要嘗試堅持一兩個,不要過度使用20。 – Wug 2012-07-18 03:58:36

+0

你用什麼來實現你的REST處理? Spring RequestMapping和ResponseBody? – MattR 2012-07-18 06:01:27

+0

@MattR是的,我使用'RequestMapping'和'ResponseBody'。 – gentlejo 2012-07-18 06:28:09

回答

3

由於您使用的春天,我建議:

  1. RuntimeException的擴展,讓例外通過拖放到控制器

  2. 如果你的異常類模型的屬性要返回在錯誤XML中,註釋異常,以便它可以作爲響應返回(如果它們都具有相同的狀態碼,則包括@ResponseStatus)。

  3. 實現你的控制器返回異常爲@ResponseBody,並確保HttpServletResponse的是正確的一個或多個@ExceptionHandler方法。喜歡的東西:

    @ExceptionHandler 
    @ResponseBody 
    public ErrorResponse handleAPIException(APIException e, HttpServletResponse response) { 
    // Set any response attributes you need... 
        return e; // or some other response 
    } 
    
+0

我剛剛申請了我的項目。好。謝謝。 – gentlejo 2012-07-18 07:01:24

相關問題