Spring REST 異常處理

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

經過ResponseEntity

經過ResponseEntity接收兩個參數,一個是對象,一個是HttpStatus.
舉例:java

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

經過ExceptionHandler註解

這裏跟前面不一樣的是,咱們註解方法的返回值不是一個ResponseEntity對象,而不是跳轉的頁面。code

@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註解的類中定義從而使異常處理對整個程序有效。orm

相關文章
相關標籤/搜索