上一篇寫過 Spring MVC 的異常處理(見 https://www.linuxidc.com/Linux/2015-06/119049.htm):捕獲異常後會轉到相應的錯誤頁面。但 REST API 通常只回傳結果與狀態碼,發生錯誤時給客戶端一個 500 加一段錯誤訊息即可。若不做處理,呼叫端遇到異常會拿到一整頁 HTML 錯誤頁,這顯然不是我們想要的。目前我知道的做法有兩種。
ResponseEntity 帶兩個參數:回傳物件與 HttpStatus。例如:
@RequestMapping(value="/customer/{id}" )
public ResponseEntity<Customer> getCustomerById(@PathVariable String id) {
Customer customer;
try {
customer = customerService.getCustomerDetail(id);
} catch (CustomerNotFoundException e) {
return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Customer>(customer, HttpStatus.OK);
}
缺點很明顯:每個 RequestMapping 方法都得塞 try-catch,太囉嗦。下面這個方式更省事。
這裡方法的回傳值不是 ResponseEntity,也不是要跳轉的頁面:
@RequestMapping(value="/customer/{id}" )
@ResponseBody
public Customer getCustomerById(@PathVariable String id) throws CustomerNotFoundException {
return customerService.getCustomerDetail(id);
}
@ExceptionHandler(CustomerNotFoundException.class)
public ResponseEntity<ClientErrorInformation> rulesForCustomerNotFound(
HttpServletRequest req, Exception e) {
ClientErrorInformation error = new ClientErrorInformation(e.toString(), req.getRequestURI());
return new ResponseEntity<ClientErrorInformation>(error, HttpStatus.NOT_FOUND);
}
總結:兩種做法中推薦第二種。它既能定義在單一 Controller 內,也能放在標註 @ControllerAdvice 的類別中,讓異常處理對整個應用生效。
--------------------------------------分割線 --------------------------------------
Spring 中如何配置 Hibernate 事務 https://www.linuxidc.com/Linux/2013-12/93681.htm
Struts2 整合 Spring 方法及原理 https://www.linuxidc.com/Linux/2013-12/93692.htm
基於 Spring 設計並實現 RESTful Web Services https://www.linuxidc.com/Linux/2013-10/91974.htm
Spring-3.2.4 + Quartz-2.2.0 集成實例 https://www.linuxidc.com/Linux/2013-10/91524.htm
使用 Spring 進行單元測試 https://www.linuxidc.com/Linux/2013-09/89913.htm
運用 Spring 註解實現 Netty 服務器端 UDP 應用程序 https://www.linuxidc.com/Linux/2013-09/89780.htm
Spring 3.x 企業應用開發實戰 PDF 完整高清掃描版+源代碼 https://www.linuxidc.com/Linux/2013-10/91357.htm
--------------------------------------分割線 --------------------------------------
Spring 的詳細介紹:請點這裡
Spring 的下載地址:請點這裡