gpt4 book ai didi

java - Spring引导不使用@ControllerAdvice覆盖异常

转载 作者:搜寻专家 更新时间:2023-11-01 03:18:26 26 4
gpt4 key购买 nike

我想从 Controller 建议方面抛出一个标准的自定义异常,但由于某种原因,我的自定义异常没有被 spring boot (1.3.3-RELEASE) 捕获。

这是我的代码:

我的测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MyApplication.class)
@WebIntegrationTest("server.port:9000")
public class ControllerTest {
private final String URL = "http://localhost:9000";

@Test
public void testCustomExceptionResponse() {
// Invoke my controller generating some exception
Map error = restTemplate.getForObject(URL+"/exception/", Map.class);
assertTrue(error.get("exception").contains("MyCustomException"));
}
}

Controller

@RequestMapping(value = "/", method = RequestMethod.GET)
public List<Object> findAll() throws Exception {
// generate whatever exception here
if (1<2) throw new IllegalIdentifierException("test whatever exception");
return ccRepository.findByActive(true);
}

用@ControllerAdvice 注释的 GlobalExceptionHandler

@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

// Catch whatever exception to throw my custom exception
@ExceptionHandler(Exception.class)
public void handleException(Exception ex) throws Exception {
logger.error("Exception Occured: ", ex);
throw new MyCustomException(ex.getLocalizedMessage());
}
}

我已经调试了代码并且正在执行 handleException 方法,但是奇怪的是正在抛出 MyCustomException 但 Controller 响应返回抛出的原始异常:

{timestamp=1473963128439, status=500, error=Internal Server Error, exception=org.hibernate.metamodel.relational.IllegalIdentifierException, message=test whatever exception, path=/exception/}

我希望有这样的东西:

exception=com.myapp.MyCustomException

据我所知, Controller 建议是捕获 Controller 中所有异常的通用方法,以绑定(bind)一些逻辑(在我的例子中是记录器),然后我通过使用自定义异常来自定义意外异常.

我是否遗漏了有关 Spring Boot 如何处理异常的任何信息?

最佳答案

这并不是 ControllerAdvice 的目的。

发生了什么

  • 你抛出 IllegalIdentifierException
  • 您在 ControllerAdvice 中捕获它
  • 自从您抛出 MyCustomException 后您的 handleException 没有完成
  • 这会在 DispatcherServlet 中引发异常,根本原因是您的原始异常 (IllegalIdentifierException)。

你应该做什么

Controller Advice 旨在在出现错误时返回有效的 Http 响应。

例如,您可以将其更改为:

@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) throws Exception {
System.out.println("Exception Occured: " + ex);
return ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Exception: " + ex.getLocalizedMessage());
}
}

因此:

  • ControllerAdvice 的方法将成功完成(返回响应);
  • DispatcherServlet 会很高兴的。
  • 原始异常不会是新错误的根本原因,现在已被成功吞噬
  • 客户端收到带有 HTTP 错误代码的消息“异常:测试任何异常”(我选择了 HttpStatus.INTERNAL_SERVER_ERROR)。

您可以使用 MockMvc 对其进行测试:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Launcher.class)
@WebAppConfiguration
public class ControllerTest {
@Autowired
private WebApplicationContext webApplicationContext;

@Test
public void testCustomExceptionResponse() throws Exception {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

mockMvc.perform(MockMvcRequestBuilders.get("/your/uri"))
.andExpect(MockMvcResultMatchers.status().isInternalServerError())
.andExpect(MockMvcResultMatchers.content().string("Exception: test whatever exception"));

assertTrue(true);
}
}

关于java - Spring引导不使用@ControllerAdvice覆盖异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39517876/

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