在上一篇中寫到了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注解的類中定義從而使異常處理對整個程序有效。
新聞熱點
疑難解答