java - How to document @ControllerAdvice handled exception using Spring REST Docs
问题描述
I have @ControllerAdvice
annotated class, which is handling BadRequestException extends RuntimeException
exception.
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:
{
"errorCode": 123,
"errorMessage: "Failure reason"
}
Is there any way to document case like this using 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.
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.
解决方案
I managed to solve the problem following this answer. When exception handler is defined for MockMvc
, my second approach works as expected.
推荐阅读
- node.js - 如何将CSV但在字段中具有\r\n和“,”的字符串转换为json?
- reactjs - 页面上的简单路由。如何设置正确的显示?
- php - 如何在 PHP 中将 XML 转换为数组
- android - 如何使单选按钮的图像居中?
- excel - 将变量从用户窗体传递到模块
- git - OpenSSL 和原生 windows 安全通道库有什么区别
- sql-server - 实体框架和 JSON.NET 序列化
- spring - Spring Boot 中用于 Amazon Aurora Serverless 的数据 API
- emacs - 重映射邪恶模式写入
- swift - Xcode 对“绑定”的期望是什么
“占位符?