![](/img/trans.png)
[英]Spring Boot - Global Custom Exception Handling Mechanism using RestControllerAdvice
[英]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.