长话短说。我的服务抛出 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
public class GlobalExceptionHandlerTest{
//
}
和测试:
@Test
public void catchesExceptionWhenEntityNotFoundWithSpecificResponse() throws Exception {
mockMvc.perform(post("/assignments")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(new ClassPathResource("rest/assign-desk.json").getInputStream().readAllBytes()))
.andExpect(status().isNotFound())
.andExpect(jsonPath("status").value(404))
.andExpect(jsonPath("exception").value("EntityNotFoundException"))
.andExpect(jsonPath("message").value("Unknown employee name: abc"));
}
谢谢大家。
关于java - Spring Boot、全局异常处理和测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50782102/