首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >spring @ExceptionHandler

spring @ExceptionHandler
EN

Stack Overflow用户
提问于 2013-03-21 15:10:04
回答 2查看 1.3K关注 0票数 0

所有,我的控制器:

代码语言:javascript
复制
@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处理方法:

代码语言:javascript
复制
@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无法处理时。谢谢!

EN

回答 2

Stack Overflow用户

发布于 2013-03-21 15:15:46

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

删除try-catch中的

代码语言:javascript
复制
throw new SQLException();

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

票数 0
EN

Stack Overflow用户

发布于 2013-03-21 15:17:02

请求处理程序方法没有抛出异常,所有的异常都是您自己处理的。

只有当请求处理程序将异常抛回spring框架时,异常处理程序才会生效。

代码语言:javascript
复制
@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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15541454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档