티스토리 뷰
api 예외처리를 위해 간단히 api컨트롤러를 만들었다.
package hello.exception.api;
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("ex")){
throw new RuntimeException("잘못된 사용자");
}
return new MemberDto(id, "hello" + id);
}
@Data
@AllArgsConstructor
static class MemberDto{
private String memberId;
private String name;
}
}
포트스맨으로 요청하면 다음과 같이 제대로 작동하고 있다. 이번엔 오류를 발생시켜 본다.
RuntimeException의 값으로 html이 결과로 나왔다. api의 에러 값은 이래선 안된다. 실패메세지를 가져와야 할 것이다. 현재는 내가 설정해둔 에러페이지를 그대로 뱉고 있다. 독립적인 프로젝트에서 쓰는 것이 아니고 상호간의 통신을 위한 것이므로 실패값을 던져주어 상대방도 그에 맞는 적절한 조취를 취할 수 있다.
일단 요청할 때에 request Header에 Accept가 application/json인 것에 주목하자. 컨트롤러도 그에 맞게 호출한다.
@RequestMapping("/error-page/500")
public String errorPage500(HttpServletResponse response, HttpServletRequest request){
printErrorInfo(request);
log.info("errorPage 500");
return "error-page/500";
}
@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> result = new HashMap<>();
Exception ex = (Exception) request.getAttribute(ERROR_EXCEPTION);
result.put("status", request.getAttribute(ERROR_STATUS_CODE));
result.put("message",ex.getMessage());
Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
return new ResponseEntity<>(result, HttpStatus.valueOf(statusCode));
}
이러 컨트롤러를 만들 때에 produces 속성을 통해 json 요청일 경우 아래의 컨트롤러로 가게 된다.
이제 등록을 해준다.
package hello.exception;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
@Component
public class WebServerCustomizer implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {
@Override
public void customize(ConfigurableWebServerFactory factory) {
ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error-page/404");
ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error-page/500");
ErrorPage errorPageEx = new ErrorPage(RuntimeException.class, "/error-page/500");
//런타임 또는 그 자식 타입의 에러일 경우 500 (500 예외가 서버내부에서 발생한 오류라는 뜻을 포함하고 있기 때문에 여기서는 예외가
//발생한 경우도 500 오류 화면으로 처리했다.
factory.addErrorPages(errorPage404,errorPage500,errorPageEx);
}
}
errorPageEx를 보면 RuntimeException 일때에 해당 컨트롤러로 이동하게 되어있다.
다음과 같은 결과가 나온다. 저 메세지는 어디에서 왔냐고?
package hello.exception.api;
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("ex")){
throw new RuntimeException("잘못된 사용자");
}
return new MemberDto(id, "hello" + id);
}
@Data
@AllArgsConstructor
static class MemberDto{
private String memberId;
private String name;
}
}
처음 컨트롤러를 만들 때에 이미 메세지를 심어 놨었다.
'dev_공부일지 > spring boot + intelliJ' 카테고리의 다른 글
HandlerExceptionResolver로 예외처리 깔끔하게 처리하기 (1) | 2023.12.05 |
---|---|
api 요청 예외처리 일때에도 부트는 자동으로 지원한다 . 아래글과 이어짐 (0) | 2023.12.04 |
스프링 부트는 자동으로 에러페이지를 작성해준다. BasicErrorController (1) | 2023.12.02 |
Interceptor를 이용할 때에 오류페이지는 타지않는 방법 (0) | 2023.12.02 |
ErrorPage 만들기 (0) | 2023.12.01 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 예외처리
- 백엔드 개발자 공부
- reject
- SpringBoot
- JPA
- 향해플러스백엔드
- filter
- React
- jpa api
- BindingResult
- 리터럴
- 백엔드 개발자 역량
- 컨트
- 향해99
- 인터셉터
- 로그인
- 스프링부트
- exception
- Intercepter
- 항해플러스
- 향해플러스
- hypertexttransferprotocol
- 스프링공부
- thymleaf
- Java
- HTTP
- ArgumentResolver
- 항해99
- react실행
- rejectValue
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
글 보관함