[英]How to document @ControllerAdvice handled exception using Spring REST Docs
I have @ControllerAdvice
annotated class, which is handling BadRequestException extends RuntimeException
exception. 我有
@ControllerAdvice
注释的类,它在处理BadRequestException extends RuntimeException
异常。
Now suppose that I have endpoint: 现在假设我有端点:
@PostMapping(value = "/createAccount")
public ResponseEntity<CreateAccountResponse> createAccount(@RequestBody @Valid CreateAccountRequest createAccountRequest) {...}
In case of unwanted scenario, endpoint throws BadRequestException
(with HTTP Status 400) which constructs error JSON object as following: 如果发生意外情况,端点将抛出
BadRequestException
(HTTP状态为400),该错误构造如下的JSON对象:
{
"errorCode": 123,
"errorMessage: "Failure reason"
}
Is there any way to document case like this using Spring REST Docs ? 有什么办法可以使用Spring REST Docs记录这种情况?
This is example of my approach: 这是我的方法的示例:
@Test
public void createAccountFailExample() {
RestDocumentationResultHandler docs = document("create-acc-fail-example",
responseFields(
fieldWithPath("errorCode").type("Integer").description("Error code"),
fieldWithPath("errorMessage").type("String").description("Error message")
)
);
org.assertj.core.api.Assertions.assertThatThrownBy(() -> this.mockMvc.perform(RestDocumentationRequestBuilders.post("/createAccount")
.contextPath("/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new CreateAccountRequest("nameTest", "surnameTest"))))
.andExpect(status().isBadRequest())
.andDo(docs)).hasCause(new BadRequestException(ServiceError.SOME_FAIL_REASON));
}
In this case test passes, but no documentation (.adoc) files are created. 在这种情况下,测试通过了,但是没有创建任何文档(.adoc)文件。
When I try something like this: 当我尝试这样的事情:
ResultActions resultActions = this.mockMvc.perform(RestDocumentationRequestBuilders.post("/createAccount")
.contextPath("/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new CreateAccountRequest("testName", "testSurname"))))
.andExpect(status().isBadRequest())
.andDo(docs);
test fails because NestedServletException
was thrown caused by BadRequestException
, and again there is no documentation created. 测试失败,因为
NestedServletException
是由BadRequestException
引发的,并且再次没有创建文档。
I managed to solve the problem following this answer . 我设法解决了这个问题 。 When exception handler is defined for
MockMvc
, my second approach works as expected. 当为
MockMvc
定义异常处理程序时,我的第二种方法可以按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.