...Rest요청에 관한 에러처리 연습
1. Rest요청 처리, Controller 선언.
import lombok.AllArgsConstructor; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @Slf4j @RestController public class ApiExceptionController { @GetMapping("/api/members/{id}") public MemberDto getMember(@PathVariable("id") String id) { if (id.equals("excp")) { throw new RuntimeException("Error Message:: Incorrect User.."); } return new MemberDto(id, "jwj" ); } @Data @AllArgsConstructor static class MemberDto { private String memberId; private String name; } } |
2. WebServerCustomizer 선언
* 스프링부트에서 발생되는 에러에 따른, 직접적인 분기처리 담당 빈(Bean)
RuntimeException발생 시, "/error-page/500" 주소로 Controller 재 요청.
3. ErrorPageController 수정
import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import javax.servlet.RequestDispatcher; @RequestMapping(value = "/error-page/500", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Map<String, Object>> errorPage500Api(HttpServletRequest request, HttpServletResponse response) { log.info("_______________API errorPage 500"); Map<String, Object> resultMap = new HashMap<>(); Exception ex = (Exception) request.getAttribute("javax.servlet.error.exception"); resultMap.put("status", request.getAttribute("javax.servlet.error.status_code")); resultMap.put("message", ex.getMessage()); Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); return new ResponseEntity(resultMap, HttpStatus.valueOf(statusCode)); } |
* produces(선행)
--> Client에서 지정한 Header설정 중, Accept에 따른 컨트롤러 우선순위 결정.
* ResponseEntity
--> Client요청에 관한 Response의 HttpBody에 직접 결과값을 넣는 것
ResponseEntity생성자("응답Body내용", Http상태코드)
4. POST MAN(RestAPI Test..)
***************
요청1
***************
Request (요청-REST)
요청유형 - HTTP GET
요청URL - http://localhost:8080/api/members/excp
REQUEST Headers
Accept | application/json | "API응답결과 JSON으로 받는다" |
(Accept / text/html -- API응답결과 Html View)
Response (응답결과)
JSON Format { "message": "Error Message:: Incorrect User", "status": 500 } |
***************
요청2
***************
Request (요청-REST)
요청유형 - HTTP GET
요청URL - http://localhost:8080/api/members/succ
REQUEST Headers
Accept | application/json | "API응답결과 JSON으로 받는다" |
(Accept / text/html -- API응답결과 Html View)
Response (응답결과)
JSON Format { "memberId": "succ", "name": "jwj" } |
--> ErrorPageController컨트롤러의
errorPage500Api (value="/error-page/500", produces = "application/json") Methods Call..
return ReposeEntity<Map<String, Object>> ::: JsonFormat
(스프링부트 기본제공 API에러처리 활용)
5. WebServerCustomizer 비 활성화
* 에러처리를 직접적으로 분기처리하는 WebServerCustomizer 비 활성화...
SpringBoot 에서 기본 제공하는 "BasicErrorController" 에서 분기를 처리하게 된다.
(org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController)
5. application.properties 수정..
* BasicErrorController 오류 컨트롤러에서 View에 전달되는, model에 포함 할 오류 정보에 관한 설정이 가능하다.
6. POST MAN(RestAPI Test..)
***************
요청3
***************
Request (요청-REST)
요청유형 - HTTP GET
요청URL - http://localhost:8080/api/members/excp
REQUEST Headers
Accept | application/json | "API응답결과 JSON으로 받는다" |
Response (응답결과)
JSON Format { "SpringBoot에서 기본제공 Rest전문" } |
***************
요청4
***************
Request (요청-REST)
요청유형 - HTTP GET
요청URL - http://localhost:8080/api/members/succ
REQUEST Headers
Accept | application/json | "API응답결과 JSON으로 받는다" |
Response (응답결과)
JSON Format { "memberId": "succ", "name": "jwj" } |
***************
요청5
***************
Request (요청-REST)
요청유형 - HTTP GET
요청URL - http://localhost:8080/api/members/excp
REQUEST Headers
Accept | text/html | "API응답결과 Html View" |
Resonse (응답결과 - 우선순위에 따른, 오류화면 View처리)
1순위. Client To Server 뷰 템플릿 (resources/templates/error/*.html)
// cf). 4xx.html, 500.html
2순위. 정적리소스 (resources/static/error/*.html)
// cf). 4xx.html, 500.html
3순위. 위 해당사항 없을시
"Path --> resources/templates/error.html"
* 스프링부트에서 기본적으로 제공하는 BasicErrorController를 활용할시,
REQUEST_HEADER의 Accept / (text/html, application/json)에 따라. 동적으로 결과가 변한다.
'SpringBoot' 카테고리의 다른 글
[SpringBoot] RestAPI요청 예외처리(2) (0) | 2021.08.26 |
---|---|
[SpringBoot] 인터셉터 생성 및 적용 (0) | 2021.07.31 |
[SpringBoot] 쿠키 생성 및 활용 (0) | 2021.07.25 |
[SpringBoot] 서블릿 필터 생성 및 적용 (0) | 2021.07.25 |
[SpringBoot] 예외처리와 에러페이지 (0) | 2021.07.25 |