两个尝试在控制器级别上捕获块

时间:2017-05-18 10:29:13

标签: java exception-handling jersey try-catch throw

我有一个案例,我需要在控制器级别上重复try..catch块。 让我提供此问题的示例代码:

AddVariable

如何重构此代码?

谢谢!

4 个答案:

答案 0 :(得分:1)

您只需为

添加特定的try/catch语句即可
List<String> loadedList = engine.findSomething(param);

调用。

您应该在致电List<String> loadedList之前声明engine.findSomething(param);,以便它在try catch范围之外,以便以后能够使用它。

List<String> loadedList = null;
try{
   loadedList = engine.findSomething(param); 
}
catch (Exception e){ // or a more specific exception if it makes sense
    // exception logging and processing    
}

答案 1 :(得分:1)

您可以从@ControllerAdvice中受益并实现全局控制器异常处理程序。

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(Exception.class)
public String handleException(HttpServletRequest request, Exception ex){
    //handle error here
    return "error";
}

为了使GlobalExceptionHandler正常工作,必须从控制器中抛出异常。

答案 2 :(得分:1)

try 
{
    List<String> loadedList = engine.findSomething(param); 

    // 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
    }

    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();

}
//You can first catch WebApplicationException before the Exception and 
//redirect the throw to the parent class
catch(WebApplicationException we) 
{
    throw we;
}
catch(Exception e)
{
    throw processException(e);
}

答案 3 :(得分:1)

另一种与davidxxx不同的方法。

将代码移到try..catch子句中。如果恰好抛出WebApplicationException然后抓住它,做你需要做的任何事情,然后再扔掉它。

try {

List<String> loadedList =
engine.findSomething(param); 

// 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
}

    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 (WebApplicationException e1){
  //log the exception
  //throw it again using throw e1
} catch (Exception e2) {
    throw processException(e2); //Helper method that avoids code duplication when preparing webException
}