Harry Harry - 2 months ago 16
reST (reStructuredText) Question

How to document error messages using Spring Rest Doc

I'm using Spring rest doc along spring mvc test to generate a restful documentation. Now I'm trying to describe the possible error messages on the resource, but I cannot find anything that will help me in the spring documentation.

What I'm trying to achieve is similar to Error 4xx section of http://apidocjs.com/example/

Any thoughts ?

Answer

Just create a test that intentionally generates an error response. And document the fields like you would with any other Spring Rest Docs test.

@Test
    public void errorExample() throws Exception {
        RestDocumentationResultHandler docs = document("Error Response",
                preprocessRequest(prettyPrint()),
                preprocessResponse(prettyPrint()),
                responseFields(
                        fieldWithPath("status").optional().type("Integer").description("Application status field."),
                        fieldWithPath("errorMsg").type("String").description("A global description of the cause of the error")        

                )
        );


        AppConfig req = getAppConfigReq(null, null, null);

        ResultActions result = this.mockMvc.perform(  post("/SomeAPICall/")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .content(this.objectMapper.writeValueAsString(req))
        );
        result.andExpect(status().is(401));
        result.andDo(docs);
    }