스프링이 아닌 순수 서블릿 컨테이너는 예외를 어떻게 처리하는지 알아보자. 서블릿은 다음 2가지 방식으로 예외 처리를 지원한다.
Exception(예외)response.sendError(HTTP 상태 코드, 오류 메시지)
main이라는 이름의 쓰레드가 실행된다. 실행 도중에 예외를 잡지 못하고 처음 실행한 main()메서드를 넘어서 예외가 던져지면, 예외 정보를 남기고 해당 쓰레드는 종료된다.WAS(여기까지 전파) <- 필터 <- 서블릿 <- 인터셉터 <- 컨트롤러(예외발생)server.error.whitelabel.enabled=false@Slf4j
@Controller
public class ServletExController {
@GetMapping("/error-ex")
public void errorEx() {
throw new RuntimeException("예외 발생!");
}
}
HTTP Status 500 – Internal Server ErrorException의 경우 서버 내부에서 처리할 수 없는 오류가 발생한 것으로 생각해서 HTTP 상태 코드 500을 반환한다.HTTP Status 404 – Not FoundHttpServletResponse가 제공하는 sendError라는 메서드를 사용해도 된다. 이것을 호출한다고 당장 예외가 발생하는 것은 아니지만, 서블릿 컨테이너에게 오류가 발생했다는 점을 전달할 수 있다.response.sendError(HTTP 상태 코드)response.sendError(HTTP 상태 코드, 오류 메시지)@GetMapping("/error-404")
public void error404(HttpServletResponse response) throws IOException {
response.sendError(404, "404 오류!");
}
@GetMapping("/error-500")
public void error500(HttpServletResponse response) throws IOException {
response.sendError(500);
}
WAS(sendError 호출 기록 확인) <- 필터 <- 서블릿 <- 인터셉터 <- 컨트롤러(response.sendError())response.sendError()를 호출하면 response내부에는 오류가 발생했다는 상태를 저장해둔다. 그리고 서블릿 컨테이너는 고객에게 응답 전에 response에 sendError()가 호출되었는지 확인한다. 그리고 호출되었다면 설정한 오류 코드에 맞추어 기본 오류 페이지를 보여준다.HTTP Status 404 – Not FoundHTTP Status 500 – Internal Server Error서블릿은
Exception(예외)가 발생해서 서블릿 밖으로 전달되거나 또는response.sendError()가 호출되었을 때 각각의 상황에 맞춘 오류 처리 기능을 제공한다. 이 기능을 사용하면 친절한 오류 처리 화면을 준비해서 고객에게 보여줄 수 있다.
<web-app>
<error-page>
<error-code>404</error-code>
<location>/error-page/404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error-page/500.html</location>
</error-page>
<error-page>
<exception-type>java.lang.RuntimeException</exception-type>
<location>/error-page/500.html</location>
</error-page>
</web-app>
web.xml이라는 파일에 위와 같이 오류 화면을 등록했다.@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");
factory.addErrorPages(errorPage404, errorPage500, errorPageEx);
}
}
response.sendError(404): errorPage404 호출response.sendError(500): errorPage500 호출RuntimeException 또는 그 자식 타입의 예외: errorPageEx 호출RuntimeException 예외가 발생하면 errorPageEx에서 지정한 /error-page/500이 호출된다.@Slf4j
@Controller
public class ErrorPageController {
@RequestMapping("/error-page/404")
public String errorPage404(HttpServletRequest request,
HttpServletResponse response) {
log.info("errorPage 404");
return "error-page/404";
}
@RequestMapping("/error-page/500")
public String errorPage500(HttpServletRequest request,
HttpServletResponse response) {
log.info("errorPage 500");
return "error-page/500";
}
}
/templates/error-page/404.html/templates/error-page/500.htmlRuntimeExceptionWAS(여기까지 전파) <- 필터 <- 서블릿 <- 인터셉터 <- 컨트롤러(예외발생)WAS '/error-page/500' 다시 요청 -> 필터 -> 서블릿 -> 인터셉터 -> 컨트롤러(/error-page/500) -> Viewrequest의 attribute에 추가해서 넘겨준다. 필요하면 오류 페이지에서 이렇게 전달된 오류 정보를 사용할 수 있다.javax.servlet.error.exception : 예외javax.servlet.error.exception_type : 예외 타입javax.servlet.error.message : 오류 메시지javax.servlet.error.request_uri : 클라이언트 요청 URIjavax.servlet.error.servlet_name : 오류가 발생한 서블릿 이름javax.servlet.error.status_code : HTTP 상태 코드
- 오류가 발생하면 오류 페이지를 출력하기 위해 WAS 내부에서 다시 한번 호출이 발생한다. 이때 필터, 서블릿, 인터셉터도 모두 다시 호출된다. 그런데 로그인 인증 체크 같은 경우를 생각해보면, 이미 한번 필터나, 인터셉터에서 로그인 체크를 완료했다. 따라서 서버 내부에서 오류 페이지를 호출한다고 해서 해당 필터나 인터셉터가 한번 더 호출되는 것은 매우 비효율적이다.
- 결국 클라이언트로 부터 발생한 정상 요청인지, 아니면 오류 페이지를 출력하기 위한 내부 요청인지 구분할 수 있어야 한다. 서블릿은 이런 문제를 해결하기 위해
DispatcherType이라는 추가 정보를 제공한다.
public enum DispatcherType {
FORWARD,
INCLUDE,
REQUEST,
ASYNC,
ERROR
}
REQUEST: 클라이언트 요청ERROR: 오류 요청FORWARD: MVC에서 배웠던 서블릿에서 다른 서블릿이나 JSP를 호출할 때RequestDispatcher.forward(request, response);INCLUDE: 서블릿에서 다른 서블릿이나 JSP의 결과를 포함할 때RequestDispatcher.include(request, response);ASYNC: 서블릿 비동기 호출log.info("dispatcherType={}", request.getDispatcherType())dispatcherType=ERROR로 나오는 것을 확인할 수 있다.dispatcherType=REQUEST이다.DispatcherType으로 구분할 수 있는 방법을 제공한다.request.getDispatcherType()을 추가한다.filterRegistrationBean.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ERROR); 이렇게 두 가지를 모두 넣으면 클라이언트 요청은 물론이고, 오류 페이지 요청에서도 필터가 호출된다. 아무것도 넣지 않으면 기본 값이 DispatcherType.REQUEST이다. 즉 클라이언트의 요청이 있는 경우에만 필터가 적용된다. 특별히 오류 페이지 경로도 필터를 적용할 것이 아니면, 기본 값을 그대로 사용하면 된다.DispatcherType.ERROR만 지정하면 된다.DispatcherType인 경우에 필터를 적용할 지 선택할 수 있었다. 그런데 인터셉터는 서블릿이 제공하는 기능이 아니라 스프링이 제공하는 기능이다. 따라서 DispatcherType과 무관하게 항상 호출된다.excludePathPatterns를 사용("/error-page/**" 추가)해서 빼주면 된다.WAS(/hello, dispatcherType=REQUEST) -> 필터 -> 서블릿 -> 인터셉터 -> 컨트롤러 -> View
1. WAS(/error-ex, dispatcherType=REQUEST) -> 필터 -> 서블릿 -> 인터셉터 -> 컨트롤러
2. WAS(여기까지 전파) <- 필터 <- 서블릿 <- 인터셉터 <- 컨트롤러(예외발생)
3. WAS 오류 페이지 확인
4. WAS(/error-page/500, dispatcherType=ERROR) -> 필터(x) -> 서블릿 -> 인터셉터(x) ->
컨트롤러(/error-page/500) -> View
DispatcherType 으로 중복 호출 제거(dispatcherType=REQUEST)excludePathPatterns("/error-page/**"))스프링 부트는 이런 과정을 모두 기본으로 제공한다.
ErrorPage를 자동으로 등록한다. 이때/error라는 경로로 기본 오류 페이지를 설정한다.
new ErrorPage(/"error"), 상태코드와 예외를 설정하지 않으면 기본 오류 페이지로 사용된다.- 서블릿 밖으로 예외가 발생하거나,
reponse.sendError(...)가 호출되면 모든 오류는/error를 호출하게 된다.BasicErrorController라는 스프링 컨트롤러를 자동으로 등록한다.
ErrorPage에서 등록한/error를 매핑해서 처리하는 컨트롤러다.ErrorMvcAutoConfiguration이라는 클래스가 오류 페이지를 자동으로 등록하는 역할을 한다.
@Component를 주석 처리하자./error를 기본 요청한다. 스프링 부트가 자동 등록한 BasicErrorController는 이 경로를 기본으로 받는다.BasicErrorController는 기본적인 로직이 모두 개발되어 있다. 개발자는 오류 페이지 화면만 BasicErrorController가 제공하는 룰과 우선순위에 따라서 등록하면 된다. 정적 HTML이면 정적 리소스, 뷰 템플릿을 사용해서 동적으로 오류 화면을 만들고 싶으면 뷰 템플릿 경로에 오류 페이지 파일을 만들어서 넣어두기만 하면 된다.resources/templates/error/500.htmlresources/templates/error/5xx.htmlstatic, public)resources/static/error/400.htmlresources/static/error/404.htmlresources/static/error/4xx.htmlerror)resources/templates/error.html* timestamp: Fri Feb 05 00:00:00 KST 2021
* status: 400
* error: Bad Request
* exception: org.springframework.validation.BindException
* trace: 예외 trace
* message: Validation failed for object='data'. Error count: 1
* errors: Errors(BindingResult)
* path: 클라이언트 요청 경로 (`/hello`)
BasicErrorController는 위의 정보를 model에 담아서 뷰에 전달한다. 뷰 템플릿은 이 값을 활용해서 출력할 수 있다.<ul>
<li th:text="|timestamp: ${timestamp}|"></li>
<li th:text="|path: ${path}|"></li>
<li th:text="|status: ${status}|"></li>
<li th:text="|message: ${message}|"></li>
<li th:text="|error: ${error}|"></li>
<li th:text="|exception: ${exception}|"></li>
<li th:text="|errors: ${errors}|"></li>
<li th:text="|trace: ${trace}|"></li>
</ul>
BasicErrorController 오류 컨트롤러에서 다음 오류 정보를 model에 포함할지 여부를 선택할 수 있다. (application.properties)server.error.include-exception=false : exception 포함 여부(true, false)server.error.include-message=never : message 포함 여부server.error.include-stacktrace=never : trace 포함 여부server.error.include-binding-errors=never : errors 포함 여부never인 부분은 다음 3가지 옵션이 있다.never: 사용하지 않음always: 항상 사용on_param: 파라미터가 있을 때 사용. 예) message=&errors=&trace=server.error.whitelabel.enabled=true: 오류 처리 화면을 못 찾을 시, 스프링 whitelabel 오류 페이지 적용server.error.path=/error: 오류 페이지 경로, 스프링이 자동 등록하는 서블릿 글로벌 오류 페이지 경로와 BasicErrorController 오류 컨트롤러 경로에 함께 사용된다.ErrorController 인터페이스를 상속 받아서 구현하거나 BasicErrorController 상속 받아서 기능을 추가하면 된다.스프링 부트가 기본으로 제공하는 오류 페이지를 활용하면 오류 페이지와 관련된 대부분의 문제는 손쉽게 해결할 수 있다.
오류 페이지는 단순히 고객에게 오류 화면을 보여주고 끝이지만, API는 각 오류 상황에 맞는 오류 응답 스펙을 정하고, JSON으로 데이터를 내려주어야 한다.
WebServerCustomizer가 다시 사용되도록 @Component애노테이션에 있는 주석을 풀자. 이제 WAS에 예외가 전달되거나, response.sendError()가 호출되면 위에 등록한 예외 페이지 경로가 호출된다.@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;
}
}
Accept가 application/json인 것을 꼭 확인.http://localhost:8080/api/members/spring){
"memberId": "spring",
"name": "hello spring"
}
http://localhost:8080/api/members/ex)@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 = MediaType.APPLICATION_JSON_VALUE의 뜻은 클라이언트가 요청하는 HTTP Header의 Accept의 값이 application/json일 때 해당 메서드가 호출된다는 것이다.Map을 만들고 status, message키에 값을 할당했다. Jackson 라이브러리는 Map을 JSON 구조로 변환할 수 있다.ResponseEntity를 사용해서 응답하기 때문에 메시지 컨버터가 동작하면서 클라이언트에 JSON이 반환된다.http://localhost:8080/api/members/ex 호출 (HTTP Header에 Accept가 application/json인 것을 꼭 확인.){
"message": "잘못된 사용자",
"status": 500
}
API 예외 처리도 스프링 부트가 제공하는 기본 오류 방식을 사용할 수 있다. 스프링 부트가 제공하는
BasicErrorController코드를 보자.
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request,
HttpServletResponse response) {}
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {}
/error 동일한 경로를 처리하는 errorHtml(), error() 두 메서드를 확인할 수 있다.
/errorHtml(): produces = MediaType.TEXT_HTML_VALUE: 클라이언트 요청의 Accept 헤더 값이 text/html인 경우에는 errorHtml()을 호출해서 view를 제공한다.
error(): 그외 경우에는 호출되고 ResponseEntity로 HTTP Body에 JSON 데이터를 반환한다.
/error를 오류 페이지로 요청한다. BasicErrorController는 이 경로를 기본으로 받는다. (server.error.path로 수정 가능, 기본 경로 /error)BasicErrorController를 사용하도록 WebServerCustomizer의 @Component를 주석처리 하자.http://localhost:8080/api/members/ex{
"timestamp": "2021-04-28T00:00:00.000+00:00",
"status": 500,
"error": "Internal Server Error",
"exception": "java.lang.RuntimeException",
"trace": "java.lang.RuntimeException: 잘못된 사용자\n\tat
hello.exception.web.api.ApiExceptionController.getMember(ApiExceptionController
.java:19...,
"message": "잘못된 사용자",
"path": "/api/members/ex"
}
BasicErrorController가 제공하는 기본 정보들을 활용해서 오류 API를 생성해준다.BasicErrorController를 확장하면 JSON 메시지도 변경할 수 있다. 그런데 API 오류는 @ExceptionHandler가 제공하는 기능을 사용하는 것이 더 나으므로 BasicErrorController를 확장해서 JSON 오류 메시지를 변경할 수 있다 정도로만 이해하자.BasicErrorController는 HTML 페이지를 제공하는 경우에는 매우 편리하다. 4xx, 5xx 등등 모두 잘 처리해준다. 그런데 API 오류 처리는 API 마다, 각각의 컨트롤러나 예외마다 서로 다른 응답 결과를 출력해야 할 수도 있다. 결과적으로 매우 세밀하고 복잡하다. 따라서 이 방법은 HTML화면을 처리할 때 사용하고, API 오류 처리는 @ExceptionHandler를 사용하자.목표
예외가 발생해서 서블릿을 넘어 WAS까지 예외가 전달되면 HTTP 상태코드가 500으로 처리된다. 발생하는 예외에 따라서 400, 404 등등 다른 상태코드로 처리하고 싶다. 오류 메시지, 형식등을 API마다 다르게 처리하고 싶다.
@GetMapping("/api/members/{id}")
public MemberDto getMember(@PathVariable("id") String id) {
if (id.equals("ex")) {
throw new RuntimeException("잘못된 사용자");
}
if (id.equals("bad")) {
throw new IllegalArgumentException("잘못된 입력 값");
}
return new MemberDto(id, "hello " + id);
}
{
"status": 500,
"error": "Internal Server Error",
"exception": "java.lang.IllegalArgumentException",
"path": "/api/members/bad"
}
http://localhost:8080/api/members/bad 호출 시 상태 코드가 500이다.HandlerExceptionResolver를 사용하면 된다. 줄여서 ExceptionResolver라 한다.ExceptionResolver로 예외를 해결해도 postHandle()은 호출되지 않는다.public interface HandlerExceptionResolver {
ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex);
}
handler: 핸들러(컨트롤러) 정보Exception ex: 핸들러(컨트롤러)에서 발생한 예외@Slf4j
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
// Exception은 ={} 안해줘도 됨
log.info("call resolver", ex);
try {
if (ex instanceof IllegalArgumentException) {
log.info("IllegalArgumentException resolver to 400");
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
ex.getMessage());
return new ModelAndView();
}
} catch (IOException e) {
log.error("resolver ex", e);
}
return null;
}
}
ExceptionResolver가 ModelAndView를 반환하는 이유는 마치 try, catch를 하듯이, Exception을 처리해서 정상 흐름 처럼 변경하는 것이 목적이다. 이름 그대로 Exception을 Resolver(해결)하는 것이 목적이다.IllegalArgumentException이 발생하면 reponse.sendError(400)를 호출해서 HTTP 상태 코드를 400으로 지정하고, 빈MoelAndView를 반환한다.HandlerExceptionResolver의 반환 값에 따른 DispatcherServlet의 동작 방식은 다음과 같다.new ModelAndView()처럼 빈ModelAndView를 반환하면 뷰를 렌더링 하지 않고, 정상 흐름으로 서블릿이 리턴된다.ModelAndView에 View, Model등의 정보를 지정해서 반환하면 뷰를 렌더링 한다.null을 반환하면, 다음 ExceptionResolver를 찾아서 실행한다. 만약 처리할 수 있는 ExceptionResolver가 없으면 예외 처리가 안되고, 기존에 발생한 예외를 서블릿 밖으로 던진다.response.sendError(xxx)호출로 변경해서 서블릿에서 상태 코드에 따른 오류를 처리하도록 위임/error가 호출됨ModelAndView에 값을 채워서 예외에 따른 새로운 오류 화면 뷰 렌더링 해서 고객에게 제공response.getWriter().println("hello");처럼 HTTP 응답 바디에 직접 데이터를 넣어주는 것도 가능하다. 여기에 JSON으로 응답하면 API 응답 처리를 할 수 있다./**
* 기본 설정을 유지하면서 추가
*/
@Override
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
resolvers.add(new MyHandlerExceptionResolver());
}
configureHandlerExceptionResolvers(..)를 사용하면 스프링이 기본으로 등록하는 ExceptionResolver가 제거되므로 주의, extendHandlerExceptionResolvers를 사용하자.http://localhost:8080/api/members/ex -> HTTP 상태 코드 500http://localhost:8080/api/members/bad -> HTTP 상태 코드 400예외를 여기서 마무리하기
예외가 발생하면 WAS까지 예외가 던져지고, WAS에서 오류 페이지 정보를 찾아서 다시/error를 호출하는 과정은 너무 복잡하다.ExceptionResolver를 활용하면 예외가 발생했을 때 이런 복잡한 과정 없이 여기에서 문제를 깔끔하게 해결할 수 있다.
//사용자 정의 예외
public class UserException extends RuntimeException {
public UserException() {
super();
}
public UserException(String message) {
super(message);
}
public UserException(String message, Throwable cause) {
super(message, cause);
}
public UserException(Throwable cause) {
super(cause);
}
protected UserException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
//예외 추가
if (id.equals("user-ex")) {
throw new UserException("사용자 오류");
}
http://localhost:8080/api/members/user-ex 호출시 UserException이 발생한다.@Slf4j
public class UserHandlerExceptionResolver 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");
String acceptHeader = request.getHeader("accept");
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
if ("application/json".equals(acceptHeader)) {
Map<String, Object> errorResult = new HashMap<>();
errorResult.put("ex", ex.getClass());
errorResult.put("message", ex.getMessage());
String result = objectMapper.writeValueAsString(errorResult);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(result);
return new ModelAndView();
} else {
// TEXT/HTML
return new ModelAndView("error/500");
}
}
} catch (IOException e) {
log.error("resolver ex", e);
}
return null;
}
}
ACCEPT값이 application/json이면 JSON으로 오류를 내려주고, 그 외 경우에는 error/500에 있는 HTML 오류 페이지를 보여준다.extendHandlerExceptionResolvers()에 resolvers.add(new UserHandlerExceptionResolver()); 추가한다.http://localhost:8080/api/members/user-ex (ACCEPT: application/json){
"ex": "hello.exception.exception.UserException",
"message": "사용자 오류"
}
http://localhost:8080/api/members/user-ex (ACCEPT: text/html)<!DOCTYPE HTML>
<html>
...
</html>
ExceptionResolver를 사용하면 컨트롤러에서 예외가 발생해도 ExceptionResolver에서 예외를 처리해버린다. 따라서 예외가 발생해도 서블릿 컨테이너까지 예외가 전달되지 않고, 스프링 MVC에서 예외 처리는 끝이 난다. 결과적으로 WAS 입장에서는 정상 처리가 된 것이다. 이렇게 예외를 이곳에서 모두 처리할 수 있다는 것이 핵심이다.ExceptionResolver를 사용하면 예외처리가 상당히 깔끔해진다.ExceptionResolver를 구현하려고 하니 상당히 복잡하다. 지금부터 스프링이 제공하는 ExceptionResolver들을 알아보자.스프링 부트가 기본으로 제공하는
ExceptionResolver는 다음과 같다.
HandlerExceptionResolverComposite에 다음 순서로 등록
- ExceptionHandlerExceptionResolver
@ExceptionHandler를 처리한다. API 예외 처리는 대부분 이 기능으로 해결한다.
- ResponseStatusExceptionResolver
- HTTP 상태 코드를 지정해준다.
예)@ResponseStatus(value = HttpStatus.NOT_FOUND)
- DefaultHandlerExceptionResolver 우선 순위가 가장 낮다.
- 스프링 내부 기본 예외를 처리한다.
ResponseStatusExceptionResolver는 예외에 따라서 HTTP 상태 코드를 지정해준다.@ReponseStatus가 달려있는 예외ResponseStatusException 예외//@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "잘못된 요청 오류")
//reason을 MessageSource에서 찾는 기능도 제공한다.
@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "error.bad")
public class BadRequestException extends RuntimeException {
}
BadRequestException 예외가 컨트롤러 밖으로 넘어가면 ResponseStatusExceptionResolver가 해당 애노테이션을 확인해서 오류 코드를 HttpStatus.BAD_REQUEST(400)으로 변경하고, 메시지도 담는다.ResponseStatusExceptionResolver 코드를 확인해보면 결국 response.sendError(statusCode, resolvedReason)를 호출하는 것을 확인할 수 있다. sendError(400)를 호출했기 때문에 WAS에서 다시 오류 페이지 (/error)를 내부 요청한다.@ResponseStatus는 개발자가 직접 변경할 수 없는 예외에는 적용할 수 없다.(애노테이션을 직접 넣어야 하는데, 내가 코드를 수정할 수 없는 라이브러리의 예외 코드 같은 곳에는 적용할 수 없다.)ResponseStatusException 예외를 사용하면 된다.@GetMapping("/api/response-status-ex1")
public String responseStatusEx1() {
throw new BadRequestException();
}
@GetMapping("/api/response-status-ex2")
public String responseStatusEx2() {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "error.bad", new
IllegalArgumentException());
}
DefaultHandlerExceptionResolver는 스프링 내부에서 발생하는 스프링 예외를 해결한다. 대표적으로 파라미터 바인딩 시점에 타입이 맞지 않으면 내부에서 TypeMismatchException이 발생하는데, 이 경우 예외가 발생했기 때문에 그냥 두면 서블릿 컨테이너까지 오류가 올라가고, 결과적으로 500 오류가 발생한다. 그런데 파라미터 바인딩은 대부분 클라이언트가 HTTP 요청 정보를 잘못 호출해서 발생하는 문제이다. HTTP에서는 이런 경우 HTTP 상태 코드 400을 사용하도록 되어 있다. DefaultHandlerExceptionResolver는 이것을 500 오류가 아니라 HTTP 상태 코드 400 오류로 변경한다.DefaultHandlerExceptionResolver.handleTypeMismatch를 보면 response.sendError(HttpServletResponse.SC_BAD_REQUEST) 코드를 확인할 수 있다. 결국 response.sendError()를 통해서 문제를 해결한다. sendError(400)을 호출했기 때문에 WAS에서 다시 오류 페이지(/error)를 내부 요청한다.HandlerExceptionResolver를 직접 사용하기는 복잡하다. API 오류 응답의 경우 response에 직접 데이터를 넣어야 해서 매우 불편하고 번거롭다. ModelAndView를 반환해야 하는 것도 API에는 잘 맞지 않는다. 스프링은 이 문제를 해결하기 위해 @ExceptionHandler라는 매우 혁신적인 예외 처리 기능을 제공한다. 그것이 아직 소개하지 않은 ExceptionHandlerExceptionResolver이다.
@ExceptionHandler애노테이션을 선언하고, 해당 컨트롤러에서 처리하고 싶은 예외를 지정해주면 된다. 해당 컨트롤러에서 예외가 발생하면 이 메서드가 호출된다. 지정한 예외 또는 그 예외의 자식 클래스는 모두 잡을 수 있다.
@Data
@AllArgsConstructor
public class ErrorResult {
private String code;
private String message;
}
@Slf4j
@RestController
public class ApiExceptionV2Controller {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class)
public ErrorResult illegalExHandle(IllegalArgumentException e) {
log.error("[exceptionHandle] ex", e);
return new ErrorResult("BAD", e.getMessage());
}
@ExceptionHandler
public ResponseEntity<ErrorResult> userExHandle(UserException e) {
log.error("[exceptionHandle] ex", e);
ErrorResult errorResult = new ErrorResult("USER-EX", e.getMessage());
return new ResponseEntity<>(errorResult, HttpStatus.BAD_REQUEST);
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler
public ErrorResult exHandle(Exception e) {
log.error("[exceptionHandle] ex", e);
return new ErrorResult("EX", "내부 오류");
}
@GetMapping("/api2/members/{id}")
public MemberDto getMember(@PathVariable("id") String id) {
if (id.equals("ex")) {
throw new RuntimeException("잘못된 사용자");
}
if (id.equals("bad")) {
throw new IllegalArgumentException("잘못된 입력 값");
}
if (id.equals("user-ex")) {
throw new UserException("사용자 오류");
}
return new MemberDto(id, "hello " + id);
}
@Data
@AllArgsConstructor
static class MemberDto {
private String memberId;
private String name;
}
}
자식예외가 발생하면 부모예외처리(), 자식예외처리() 둘다 호출 대상이 된다. 둘 중 더 자세한 것이 우선권을 가지므로 자식예외처리()가 호출된다. 물론 부모예외가 호출되면 부모예외처리()만 호출 대상이 되므로 부모예외처리()가 호출된다.http://localhost:8080/api2/members/badIllegalArgumentException 예외가 컨트롤러 밖으로 던져진다.ExceptionResolver가 작동한다. 가장 우선순위가 높은 ExceptionHandlerExceptionResolver가 실행된다.ExceptionHandlerExceptionResolver는 해당 컨트롤러에 IllegalArgumentException을 처리할 수 있는 @ExceptionHandler가 있는지 확인한다.illegalExHandle()를 실행한다. @RestController이므로 illegalExHandle()에도 @ResponseBody 가 적용된다. 따라서 HTTP 컨버터가 사용되고, 응답이 JSON({"code": "BAD", "message": "잘못된 입력 값"})으로 반환된다.@ResponseStatus(HttpStatus.BAD_REQUEST)를 지정했으므로 HTTP 상태 코드 400으로 응답한다.http://localhost:8080/api2/members/user-ex@ExceptionHandler에 예외를 생략하면 메서드 파라미터의 예외가 지정된다. 여기서는 UserException을 사용한다.ResponseEntity를 사용해서 HTTP 메시지 바디에 직접 응답한다. 물론 HTTP 컨버터가 사용된다.ResponseEntity를 사용하면 HTTP 응답 코드를 프로그래밍해서 동적으로 변경할 수 있다. 앞서 살펴본 @ResponseStatus는 애노테이션이므로 HTTP 응답 코드를 동적으로 변경할 수 없다.http://localhost:8080/api2/members/exthrow new RuntimeException("잘못된 사용자") 이 코드가 실행되면서, 컨트롤러 밖으로 RuntimeException이 던져진다.RuntimeException은 Exception의 자식 클래스이다. 따라서 exHandle()이 호출된다.@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)로 HTTP 상태 코드를 500으로 응답한다.@ExceptionHandler({AException.class, BException.class})
public String ex(Exception e) {
log.info("exception e", e);
}
@ExceptionHandler(ViewException.class)
public ModelAndView ex(ViewException e) {
log.info("exception e", e);
return new ModelAndView("error");
}
ModelAndView를 사용해서 오류 화면(HTML)을 응답하는데 사용할 수도 있다.@ExceptionHandler에는 마치 스프링의 컨트롤러의 파라미터, 응답처럼 다양한 파라미터와 응답을 지정할 수 있다. 자세한 파라미터와 응답은 공식 메뉴얼을 참고하자.
@ExceptionHandler를 사용해서 예외를 깔끔하게 처리할 수 있게 되었지만, 정상 코드와 예외 처리 코드가 하나의 컨트롤러에 섞여 있다.@ControllerAdvice또는@RestControllerAdvice를 사용하면 둘을 분리할 수 있다.
@ControllerAdvice는 대상으로 지정한 여러 컨트롤러에 @ExceptionHandler, @InitBinder 기능을 부여해주는 역할을 한다.@ControllerAdvice에 대상을 지정하지 않으면 모든 컨트롤러에 적용된다. (글로벌 적용)@RestControllerAdvice는 @ControllerAdvice와 같고, @ResponseBody가 추가되어 있다.// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = RestController.class)
public class ExampleAdvice1 {}
// Target all Controllers within specific packages
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}
// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = {ControllerInterface.class,
AbstractController.class})
public class ExampleAdvice3 {}