歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Spring REST 異常處理

Spring REST 異常處理

日期:2017/3/1 9:28:20   编辑:Linux編程

在上一篇中寫到了Spring MVC的異常處理【見 http://www.linuxidc.com/Linux/2015-06/119049.htm】,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}" )
@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事務 http://www.linuxidc.com/Linux/2013-12/93681.htm

Struts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm

基於 Spring 設計並實現 RESTful Web Services http://www.linuxidc.com/Linux/2013-10/91974.htm

Spring-3.2.4 + Quartz-2.2.0集成實例 http://www.linuxidc.com/Linux/2013-10/91524.htm

使用 Spring 進行單元測試 http://www.linuxidc.com/Linux/2013-09/89913.htm

運用Spring注解實現Netty服務器端UDP應用程序 http://www.linuxidc.com/Linux/2013-09/89780.htm

Spring 3.x 企業應用開發實戰 PDF完整高清掃描版+源代碼 http://www.linuxidc.com/Linux/2013-10/91357.htm

--------------------------------------分割線 --------------------------------------

Spring 的詳細介紹:請點這裡
Spring 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved