长话短说,我的服务会抛出EntityNotFound异常。默认情况下,Spring Boot不知道这是什么异常以及如何处理它,只会显示“500 Internal Server Error”。
我别无选择,只能实现自己的异常处理机制。
有几种方法可以解决这个问题,我选择使用@ControllerAdvice和@ExceptionHandler方法。
我认为,这个测试应该通过,但它没有通过。
欢迎任何想法。 谢谢!
我别无选择,只能实现自己的异常处理机制。
有几种方法可以解决这个问题,我选择使用@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());
}
我认为,这个测试应该通过,但它没有通过。
欢迎任何想法。 谢谢!