【发布时间】:2017-05-18 10:29:12
【问题描述】:
我有一个案例,我需要在控制器级别重复 try..catch 块。 让我提供此问题的示例代码:
List<String> loadedList =
engine.findSomething(param); //At this point we can obtain Exception, so this code block we should move to existing try block or create another.. but the problem if we move this to try block below, the WebApplicationException that throws in condition below will be catched in existing try block..
// if not found - return NOT_FOUND.
if (CollectionUtils.isEmpty(loadedList)) {
log.info(errorMessage);
throw new WebApplicationException(Response.status(Status.NOT_FOUND).entity(errorMessage).type("text/plain").build()); //exception from Jersey lib
}
try {
for (String item : loadedList) {
//some business logic
//I know that on controller layer we should avoid business logic but it is not my code and I can not change it..
}
return Response.ok().build();
} catch (Exception e) {
throw processException(e); //Helper method that avoids code duplication when preparing webException
}
如何重构这段代码?
谢谢!
【问题讨论】:
-
这是一个 Spring 控制器吗?
-
"但它不是我的代码,我无法更改它.." 但是你想重构它吗?
-
是的,它是 Spring 控制器,我无法移动业务逻辑,因为它不在当前任务的范围内:)
-
可以捕获异常,检查是否是WebApplicationException,如果是则再次抛出。
标签: java exception-handling jersey try-catch throw