gpt4 book ai didi

java - Controller 级别的两个 try catch block

转载 作者:行者123 更新时间:2023-12-01 17:56:55 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com