[인덱스 만들기] 에서 ErrorsResource 부분 질문입니다.
758
작성한 질문수 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())
Spring 시큐리티 관련해서 WebSecurityConfigurationAdapter
0
73
1
junit5 사용하시는 분들
0
87
1
자바 빈 스펙을 준수하는지 체크하는 테스트
0
236
2
REST API 개발 중 비즈니스 로직 적용 부분의 JSON 에러
0
242
1
스프링 부트 3버전에서의 실습
0
190
1
java.lang.AssertionError: Status
0
531
2
spring doc 관련 파일 생성 관련 배포 관련 질문 드립니다.
0
287
1
섹션2 201응답받기 부분 테스트 404에러 질문입니다
0
741
1
강의 자료가 404입니다 확인 부탁 드려요!
0
477
1
연동 DB문의
0
358
1
이벤트 Repository강의 중 Event 클래스에 private Integer Id; 위치 질문
0
505
1
(Mac) postgressql 관련하여 port kill 해도 다시 살아나는 경우
0
380
0
maven으로 생성한 docs파일(index.html)에서의 not found 오류 질문
0
621
1
테스트 오류 질문드립니다.
0
512
1
docs 요청값이 반영이 안되네요... (해결)
-1
394
1
psql 적용 후 에러
0
818
2
mvn package 시 다음과 같은 에러가 나시면
0
765
2
Event에 Account manager를 추가했으면 문서화 필요
0
274
1
2년 훨씬 전 부터 Restlet-> Talend API 로 바뀌었습니다~
1
473
1
asciidoc 추가 스니펫 에러 해결법
0
400
1
_links 는 현재 fieldWithPath 를 해주지 않아도 됩니다.
0
424
3
깃랩 처음 사용자를 위한 index.adoc raw 보는 법
0
332
1
eclipse 쓰시는 분을 위한 maven-resources-plugin 팁
0
333
1
부트 + jupiter 인 경우 설정법
0
342
1





