国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Spring REST 異常處理

2019-11-15 00:38:11
字體:
來源:轉載
供稿:網友
SPRing REST 異常處理

在上一篇中寫到了Spring MVC的異常處理,SpringMVC捕獲到異常之后會轉到相應的錯誤頁面,但是我們REST API ,一般只返回結果和狀態碼,比如發生異常,只向客戶端返回一個500的狀態碼,和一個錯誤消息。如果我們不做處理,客戶端通過REST API訪問,發生異常的話,會得到一個錯誤頁面的html代碼。。。這時候怎么做呢, 我現在所知道的就兩種做法

通過ResponseEntity

通過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語句塊,比較麻煩,下面介紹個更簡單點的方法

通過ExceptionHandler注解

這里跟前面不同的是,我們注解方法的返回值不是一個ResponseEntity對象,而不是跳轉的頁面。

@RequestMapping(value="/customer/{id}" )@ResponseBodypublic 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注解的類中定義從而使異常處理對整個程序有效。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 大庆市| 肇州县| 突泉县| 阿拉善盟| 京山县| 江源县| 辰溪县| 永德县| 沽源县| 贡山| 哈巴河县| 大理市| 金沙县| 岳阳市| 黑山县| 金昌市| 建始县| 建水县| 两当县| 鄂伦春自治旗| 柳州市| 大洼县| 泉州市| 广昌县| 岳池县| 武宁县| 通江县| 班戈县| 娄烦县| 长治市| 青浦区| 务川| 巴塘县| 余江县| 曲沃县| 南华县| 德保县| 濮阳市| 周宁县| 寿阳县| 喜德县|