spring @ExceptionHandler

时间:2013-03-21 07:10:04

标签: spring exception annotations

全部 我的控制员:

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

2 个答案:

答案 0 :(得分:0)

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

删除围绕

的try-catch
throw new SQLException();

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

答案 1 :(得分: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;
}