스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 대시보드 - 인프런 | 강의 (inflearn.com)
스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 - 인프런 | 강의
웹 애플리케이션 개발에 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. MVC 2편에서는 MVC 1편의 핵심 원리와 구조 위에 실무 웹 개발에 필요한 모든 활용 기술들을 학습할 수 있
www.inflearn.com
API 예외 처리
HTML 페이지: 오류 페이지만 있으면 됨
API: 각 오류 상황에 맞는 응답 스펙을 정하고 JSON으로 전송
(웹 브라우저가 아니면 HTML을 직접 받아서 할 수 있는 것 거의 없음)
에러 직접 처리
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@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");
// 에러 받아옴
Exception ex = (Exception) request.getAttribute(ERROR_EXCEPTION);
// 응답 객체 생성
Map<String, Object> result = new HashMap<>();
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));
}
|
cs |
Header의 Accept가 */*이면 그냥 HTML
Header의 Accept가 application/json이면 JSON
스프링 부트 기본 오류 처리
WebServerCustomizer가 없어도 Header의 Accept가 application/json이면 스프링 부트에서 json 형식으로 전송
(기본 경로: /error)
{
"timestamp": "2021-07-23T07:22:22.285+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/members/ex"
}
HTML 화면 처리: BasicErrorController
API 오류 처리: @ExceptionHandler
HandlerExceptionResolver
컨트롤러(핸들러) 밖으로 던져진 예외를 해결 및 동작 방식 변경
적용 전: preHandle -> 컨트롤러 -> afterCompletion -> WAS
적용 후: preHandle -> 컨트롤러 -> ExceptionResolver -> afterCompletion -> WAS
※ ExceptionResolver로 예외를 해결해도 postHandle()은 호출되지 않음
MyHandlerExceptionResolver
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
@Slf4j
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
try {
if(ex instanceof IllegalArgumentException){
log.info("IllegalArgumenException resolver to 400");
// IllegalArgumentException을 받으면 400에러를 전송
response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
// return을 정상적으로 해서 예외를 삼킴
return new ModelAndView();
}
} catch (IOException e) {
log.error("resolver ex", e);
}
return null;
}
}
|
cs |
MyHandlerExceptionResolver 핸들러 등록
1
2
3
4
5
6
7
|
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
resolvers.add(new MyHandlerExceptionResolver());
}
}
|
cs |
ExceptionResolver가 ModelAndView 반환
: try, catch 하듯이 Exception을 처리해서 정상 흐름처럼 변경 (Exception을 Resolve)
반환 값에 따른 동작 방식
① 빈 ModelAndView: 뷰를 렌더링 하지 않고, 정상 흐름으로 서블릿 리턴
② ModelAndView 지정: ModelAndView 에 View , Model 등의 정보를 지정해서 반환하면 뷰를 렌더링
③ null: 다음 ExceptionResolver 를 찾아서 실행. 처리할 수 있는 ExceptionResolver 가 없으면 예외 처리가 안되고, 기존에 발생한 예외를 서블릿 밖으로 던짐
UserExceptionHandlerResolver
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
|
@Slf4j
public class UserExceptionHandlerResolver implements HandlerExceptionResolver {
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
try{
if (ex instanceof UserException) {
log.info("UserException resolver to 400");
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
// 헤더에 따라서 json, html 선택
String acceptHeader = request.getHeader("accept");
if (acceptHeader.equals("application/json")) {
Map<String, Object> errorResult = new HashMap<>();
errorResult.put("ex", ex.getClass());
errorResult.put("message", ex.getMessage());
// 객체를 String으로 변경
String result = objectMapper.writeValueAsString(errorResult);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(result);
return new ModelAndView();
}
else {
return new ModelAndView("error/500");
}
} catch(IOException e){
log.error("resolver ex", e);
}
return null;
}
}
|
cs |
UserExceptionHandlerResolver 추가
1
2
3
4
5
6
7
8
|
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
resolvers.add(new MyHandlerExceptionResolver());
resolvers.add(new UserExceptionHandlerResolver());
}
}
|
cs |
예외를 여기서 마무리하기
예외 발생: 컨트롤러 -> WAS -> 오류 페이지 찾음 -> 다시 /error 호출
ExceptionResolver 활용: 컨트롤러에서 예외 발생해도 ExceptionResolver에서 예외 처리. 서블릿 컨테이너까지 예외가 전달되지 않고, 스프링 MVC에서 예외 처리 끝남. (정상 처리)
스프링이 제공하는 ExceptionResolver
스프링 부트 제공
- ExceptionHandlerExceptionResolver
- ResponseStatusExceptionResolver
- DefaultHandlerExceptionResolver
① ResponseStatusExceptionResolver
예외에 따라서 HTTP 상태 코드 지정
- @ResponseStatus가 달려있는 예외
- ResponseStatusException 예외
예외 발생 컨트롤러
1
2
3
4
|
@GetMapping("/api/response-status-ex1")
public String responseStatusEx1() {
throw new BadRequestException();
}
|
cs |
여기서 처리 (상태 코드 변경 가능)
1
2
3
|
@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "잘못된 요청 오류")
public class BadRequestException extends RuntimeException {
}
|
cs |
메시지 기능
reason을 MessageSource에서 찾는 기능
1
2
3
4
|
@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "error.bad")
public class BadRequestException extends RuntimeException {
}
|
cs |
messages.properties
error.bad=잘못된 요청 오류입니다.
@ResponseStatus: 는 라이브러리의 예외 코드와 같이 개발자가 직접 변경할 수 없는 예외에는 적용할 수 없다.
애노테이션을 사용하기 때문에 동적으로 변경하는 것이 어려움.
=> ResponseStatusException으로 처리
1
2
3
4
|
@GetMapping("/api/response-status-ex2")
public String responseStatusEx2() {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "error.bad", new IllegalArgumentException());
}
|
cs |
② DefaultHandlerExceptionResolver
스프링 내부에서 발생하는 스프링 예외를 처리
ex. 파라미터 바인딩 시점에 타입이 맞지 않음 -> TypeMismatchException
정리
1. ExceptionHandlerExceptionResolver 다음 시간에
2. ResponseStatusExceptionResolver HTTP 응답 코드 변경
3. DefaultHandlerExceptionResolver 스프링 내부 예외 처리
'오늘 배운 것' 카테고리의 다른 글
[스프링 MVC 2] 스프링 타입 컨버터(2), 파일 업로드 (0) | 2021.07.26 |
---|---|
[스프링 MVC 2] API 예외 처리(2), 스프링 타입 컨버터 (0) | 2021.07.26 |
[스프링 MVC 2] 예외 처리와 오류 페이지 (0) | 2021.07.23 |
[스프링 MVC 2] 로그인 처리2 - 필터, 인터셉터 (0) | 2021.07.22 |
[스프링 MVC 2] 로그인 처리1 - 쿠키, 세션 (0) | 2021.07.20 |