java - Controller 级别的两个 try catch block

标签 java exception jersey try-catch throw

我有一个情况,我需要在 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/

相关文章:

java - @XmlSeeAlso 的表现

java - jackson 2.1.3 的 web.xml

java - 如何在 Hibernate 中注释 PostgreSQL GIN 索引

java - 测量 session 属性对象的大小

java 轻量级调试器

java - 无法捕获 org.hibernate.StaleObjectStateException

java - Rest Web 服务中的 AbstractMethodError

Java 录音和混音器设置

exception - openNI干扰cvCreateCameraCapture()

jersey - JAX-RS 中特定于 URI 的 ExceptionMapper