0

所有,我的控制器:

@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;
}

我在同一个控制器中的执行句柄方法:

@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 无法处理时。谢谢!

4

2 回答 2

0

你捕获Exception(所有异常),然后抛出一个新的SQLException. 然后您立即捕获该 SQLException 并打印其堆栈跟踪。搜索方法永远不会抛出任何异常。

删除 try-catch 周围

throw new SQLException();

它应该可以工作。但是请重新考虑您的异常处理(不要捕获所有异常然后抛出另一种类型的异常)。

于 2013-03-21T07:15:46.133 回答
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;
}
于 2013-03-21T07:17:01.580 回答