【发布时间】:2018-11-19 18:45:28
【问题描述】:
长话短说。我的服务抛出 EntityNotFound 异常。默认情况下,Spring boot 不知道这是什么类型的异常以及如何处理它,只是显示“500 Internal Server Error”。
我别无选择,只能实现自己的异常处理机制。
使用 Spring Boot 有多种方法可以解决此问题。我选择将@ControllerAdvice 与@ExceptionHandler 方法一起使用。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity<ErrorDetails> handleNotFound(EntityNotFoundException exception, HttpServletRequest webRequest) {
ErrorDetails errorDetails = new ErrorDetails(
new Date(),
HttpStatus.NOT_FOUND,
exception,
webRequest.getServletPath());
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
}
所以当抛出异常时,新的处理程序会捕获异常并返回一个包含消息的漂亮 json,例如:
{
"timestamp": "2018-06-10T08:10:32.388+0000",
"status": 404,
"error": "Not Found",
"exception": "EntityNotFoundException",
"message": "Unknown employee name: test_name",
"path": "/assignments"
}
实施 - 没那么难。最难的部分是测试。
首先,在测试时 spring 似乎并不知道测试模式下的新处理程序。 我如何告诉 spring 知道处理此类错误的新实现?
@Test
public void shouldShow404() throws Exception {
mockMvc.perform(post("/assignments")
.contentType(APPLICATION_JSON_UTF8_VALUE)
.content(new ClassPathResource("rest/assign-desk.json").getInputStream().readAllBytes()))
.andExpect(status().isNotFound());
}
在我看来,这个测试应该通过,但它没有。
欢迎提出任何想法。谢谢!
【问题讨论】:
-
你是如何初始化测试类的?你用的是什么跑步者?
-
"@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc'code"
标签: java spring spring-boot testing error-handling