繁体   English   中英

Spring Boot,全局异常处理和测试

[英]Spring Boot, Global Exception Handling and Testing

长话短说。 我的服务抛出 EntityNotFound 异常。 默认情况下,Spring Boot 不知道那是什么类型的异常以及如何处理它,而只是显示“500 内部服务器错误”。

我别无选择,只能实现自己的异常处理机制。

有几种方法可以使用 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"));
}

谢谢你们。

问题github 问题的可能重复。 不知道你是如何设置测试类的。 但是,如果您的测试类使用 WebMvcTest 进行注释,则应注册所有控制器和控制器建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM