我有一个情况,我需要在 Controller 级别重复 try..catch block 。 让我提供此问题的示例代码:
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
}
如何重构这段代码?
谢谢!
最佳答案
您可以从 @ControllerAdvice 中受益并实现全局 Controller 异常处理程序。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public String handleException(HttpServletRequest request, Exception ex){
//handle error here
return "error";
}
为了让 GlobalExceptionHandler 正常工作,异常必须从 Controller 中抛出。
关于java - Controller 级别的两个 try catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44045285/