2013-03-21 62 views
0

所有, 我的控制器:在同一個控制器春天@ExceptionHandler

@RequestMapping(method = RequestMethod.GET, value = "/search") 
@ResponseBody 
public CemeteryRestResponse<List<String>> search(
     @RequestParam("location") Location location) { 
    CemeteryRestResponse<List<String>> restResponse = new CemeteryRestResponse<List<String>>(); 
    restResponse.setBody(new ArrayList<String>()); 
    Long a = Long.valueOf("aaaa"); 
    try { 
     for (PublicCemetery cemetery : cemeteryDao.findByLocation(location)) { 
      restResponse.getBody().add(cemetery.getNameCn()); 
     } 
    } catch (Exception e) { 
     try { 
      throw new SQLException(); 
     } catch (SQLException e1) { 
      e1.printStackTrace(); 
     } 
    } 
    restResponse.setSuccess(true); 
    return restResponse; 
} 

我execption處理方法:

@ExceptionHandler(value = { Exception.class, SQLException.class, 
     IllegalArgumentException.class, NumberFormatException.class }) 
@ResponseBody 
public CemeteryRestResponse<String> exceptionHandler(Exception e, 
     SQLException e2, IllegalArgumentException e3, 
     NumberFormatException e4) { 
    CemeteryRestResponse<String> restResponse = new CemeteryRestResponse<String>(); 
    restResponse.setFailureMessageCn("data base exception"); 

    restResponse.setSuccess(false); 
    return restResponse; 
} 

當搜索方法trhow的SQLException和NumberFormatException的@ExceptionHandler無法處理。 謝謝!

+0

你是不是從方法拋出一個異常,所有的方法都使用'try..catch'方法 – 2013-03-21 07:16:09

回答

0

你抓Exception(所有例外),然後拋出一個新的SQLException。然後立即捕獲該SQLException並打印其堆棧跟蹤。搜索方法將從不拋出任何異常。

刪除的try-catch周圍

throw new SQLException(); 

,它應該工作。但請重新考慮您的異常處理(不要捕捉所有異常,然後拋出另一種異常)。

+0

它仍然無法正常工作處理。 如果需要xml配置? – wilson 2013-03-21 08:14:52

0

請求處理程序方法沒有拋出異常,您自己處理所有異常。

只有當請求處理程序拋出異常返回到Spring框架時,異常處理程序纔會生效。

@RequestMapping(method = RequestMethod.GET, value = "/search") 
@ResponseBody 
public CemeteryRestResponse<List<String>> search(
     @RequestParam("location") Location location) throws Exception{ 
    CemeteryRestResponse<List<String>> restResponse = new CemeteryRestResponse<List<String>>(); 
    restResponse.setBody(new ArrayList<String>()); 
    Long a = Long.valueOf("aaaa"); 
    for (PublicCemetery cemetery : cemeteryDao.findByLocation(location)) { 
     restResponse.getBody().add(cemetery.getNameCn()); 
    } 
    restResponse.setSuccess(true); 
    return restResponse; 
} 
+0

謝謝你的回覆。 但你的回覆仍然無法處理。 如果需要xml配置? – wilson 2013-03-21 08:09:36