• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

[인덱스 만들기] 에서 ErrorsResource 부분 질문입니다.

20.10.02 22:16 작성 조회수 455

1

안녕하세요.

강의 목차 중 [인덱스 만들기] 부분 진행하다가 질문이 있습니다.

현재 Spring boot 2.3.4 버전 사용중입니다.

ErrorsResource를 만들고, EventController.java파일에서

if(errors.hasErrors()){
            return ResponseEntity.badRequest().body(new ErrorsResource(errors));
        }
        eventValidator.validate(eventDTO, errors);
        if(errors.hasErrors()){
            return ResponseEntity.badRequest().body(new ErrorsResource(errors));
        }

여기서 return body에 new ErrorsResource(errors)를 추가하니까 500에러가 발생했습니다.

제가 어떤 부분을 놓치고있는 건지 찾아봐도 도저히 모르겠습니다..

## error 내용

2020-10-02 22:09:06.151  WARN 14548 --- [           main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Can not start an array, expecting field name (context: Object); nested exception is com.fasterxml.jackson.core.JsonGenerationException: Can not start an array, expecting field name (context: Object)]

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /api/events/
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"343"]
             Body = {"name":"spring","description":"rest api dev with spring","beginEnrollmentDateTime":"2020-10-02T23:28:00","closeEnrollmentDateTime":"2020-10-01T23:28:00","beginEventDateTime":"2020-10-02T23:28:00","endEventDateTime":"2020-10-03T23:28:00","location":"kangNam Station D2 startUP factory","basePrice":10000,"maxPrice":200,"limitOfEnrollment":100}
    Session Attrs = {}

Handler:
             Type = com.kyeongmin.demorestapitest.events.EventController
           Method = com.kyeongmin.demorestapitest.events.EventController#createEvent(EventDTO, Errors)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotWritableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 500
    Error message = null
          Headers = [Content-Type:"application/hal+json"]
     Content type = application/hal+json
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

아래는 ErrorsResource.java 코드 부분입니다.

github 주소입니다 https://github.com/gkm2019/rest-api-test-with-spring

답변 2

·

답변을 작성해보세요.

5

좋은 질문 감사합니다. 스프링 부트 2.3으로 올라가면서 Jackson 라이브러리가 더이상 Array부터 만드는걸 허용하지 않습니다.

2020-10-02 22:09:06.151  WARN 14548 --- [           main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Can not start an array, expecting field name (context: Object); nested exception is com.fasterxml.jackson.core.JsonGenerationException: Can not start an array, expecting field name (context: Object)]

ErrorSerializer 코드에 한줄만 추가해주시면 됩니다.

jsonGenerator.writeFieldName("errors");
jsonGenerator.writeStartArray();

그런 다음 테스트코드를 content[0]이 아니라 errors[0]으로 조회하도록 고치면 되구요.

this.mockMvc.perform(post("/api/events/")
.contentType(MediaType.APPLICATION_JSON)
.content(this.objectMapper.writeValueAsString(eventDTO)))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("errors[0].objectName").exists())
.andExpect(jsonPath("errors[0].field").exists())
.andExpect(jsonPath("errors[0].code").exists())
.andExpect(jsonPath("_links.index").exists())

0

popo2019님의 프로필

popo2019

질문자

2020.10.03

빠른 답변 너무 감사드립니다.

오류 첫줄을 놓쳤네요... 다음 부턴 더 꼼꼼히 읽도록 하겠습니다.

감사합니다 :)