본문 바로가기
[ JAVA ]/JAVA Spring

[ Spring ] API Exception Handling - ExceptionResolver

by 환이s 2024. 1. 25.


이전 포스팅에 이어서 API Exception Handling 진행하겠습니다.

 

Spring이 제공하는 ExceptionResolver를 사용하기 전에 직접 ExceptionResolver를 구현해 봤지만 상당히 복잡한 관계로 사용하기가 어려웠다.

 

이 포스팅을 읽기 전에 아래 글을 읽고 오면 이해하는데 조금이나마 도움이 될 거 같다.

 

[ Spring ] API Exception Handling

API Exception Handling - start 이전 포스팅에서 Servlet Exception Handling 하는 방법에 대한 포스팅을 작성했는데, API 예외 처리는 어떻게 해야 할까? HTML 페이지의 경우 4xx, 5xx와 같은 오류 페이지만 있으면

drg2524.tistory.com


API Exception Handling - ExceptionResolver 1

 

Spring Boot가 기본으로 제공하는 ExceptionResolver는 다음과 같다.

 

HandlerExceptionResolverComposite에 다음 순서로 등록

  1. ExceptionHandlerExceptionResolver
  2. ResponseStatusExceptionResolver
  3. DefaultHandlerExceptionResolver -> 우선 순위가 가장 낮다.

 

  • ExceptionHandlerExceptionResolver
    • @ExceptionHandler을 처리한다.
    • API 예외 처리는 대부분 이 기능으로 해결한다. (조금 뒤에 자세히 설명한다.)
  • ResponseStatusExceptionResolver
    • HTTP 상태 코드를 지정해 준다.
      • ex) @ResponseStatus(value = HttpStatus.NOT_FOUND)

  • DefaultHandlerExceptionResolver
    • Spring 내부 기본 예외를 처리한다.

 

먼저 가장 쉬운 ResponseStatusExceptionResolver부터 알아보자.

■ ResponseStatusExceptionResolver

ResponseStatusExceptionResolver는 예외에 따라서 HTTP 상태 코드를 지정해 주는 역할을 한다.

 

다음 주 가지 경우를 처리한다.

 

  • @ResponseStatus가 달려있는 예외
  • ResponseStatusException 예외

 

하나씩 확인해 보자.

 

예외에 다음과 같이 @ResponseStatus 애노테이션을 적용하면 HTTP 상태 코드를 변경해 준다.

 

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "잘못된 요청 오류")
public class BadRequestException extends RuntimeException {
}

 

BadRequestException 예외가 컨트롤러 밖으로 넘어가면 ResponseStatusExceptionResolver 예외가

해당 애노테이션을 확인해서 오류 코드를 HttpStatus.BAD_REQUEST(400)으로 변경하고, 메시지도 담는다.

 

ResponseStatusExceptionResolver 코드를 확인해 보면

결국 response.sendError(statusCode, resolvedReason)를 호출하는 것을 확인할 수 있다.

 

sendError(400)를 호출했기 때문에 WAS에서 다시 오류 페이지(/error)를 내부 요청한다.

 

  • ApiExceptionController - 추가
@GetMapping("/api/response-status-ex1")
public String responseStatusEx1() {
	 throw new BadRequestException();
}

 

Postman으로 실행해서 결과를 확인해 보면 다음과 같은 결과가 출력된다.

{
     "status": 400,
     "error": "Bad Request",
     "exception": "hello.exception.exception.BadRequestException",
     "message": "잘못된 요청 오류",
     "path": "/api/response-status-ex1"
}

 

추가적으로 reasonMessageSource에서 찾는 기능도 제공한다.

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

//@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "잘못된 요청 오류")
@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "error.bad")
public class BadRequestException extends RuntimeException {
}

 

기존의 @ResponseStatus 애노테이션을 주석 처리하고 reason = "error.bad"

properties에서 읽을 수 있는 값을 입력한다.

 

  • messages.properties
error.bad=잘못된 요청 오류입니다. 메시지 사용

 

다시 Postman으로 결과를 확인해보면

{
 "status": 400,
 "error": "Bad Request",
 "exception": "hello.exception.exception.BadRequestException",
 "message": "잘못된 요청 오류입니다. 메시지 사용",
 "path": "/api/response-status-ex1"
}

 

정상적으로 message 출력되는 걸 확인할 수 있다.

 

■  ResponseStatusException

 

@ResponseStatus는 개발자가 직접 변경할 수 없는 예외에는 적용할 수 없다.

(애노테이션을 직접 넣어야 하는데, 내가 코드를 수정할 수 없는 라이브러리의 예외 코드 같은 곳에는 적용할 수 없다.)

 

추가로 애노테이션을 사용하기 때문에 조건에 따라 동적으로 변경하는 것도 어렵다.

이때는 ResponseStatusException 예외를 사용하면 된다.

 

  • ApiExceptionController - 추가
@GetMapping("/api/response-status-ex2")
public String responseStatusEx2() {

	 throw new ResponseStatusException(HttpStatus.NOT_FOUND, "error.bad", new IllegalArgumentException());

}

 

 

{
     "status": 404,
     "error": "Not Found",
     "exception": "org.springframework.web.server.ResponseStatusException",
     "message": "잘못된 요청 오류입니다. 메시지 사용",
     "path": "/api/response-status-ex2"
}

 


API Exception Handling - ExceptionResolver 2

 

이번에는 DefaultHandlerExceptionResolver를 살펴보자.

 

DefaultHandlerExceptionResolver는 Spring 내부에서 발생하는 Spring 예외를 해결한다.

대표적으로 파라미터 바인딩 시점에 타입이 맞지 않으면 내부에서 TypeMismatchException이 발생하는데,

 

이 경우 예외가 발생했기 때문에 그냥 두면 서블릿 컨테이너까지 오류가 올라가고,

결과적으로 500 오류가 발생한다.

 

그런데 파라미터 바인딩은 대부분 클라이언트가 HTTP 요청 정보를 잘못 호출해서 발생하는 문제이다.

HTTP에서는 이런 경우 HTTP 상태 코드 400을 사용하도록 되어 있다.

 

DefaultHandlerExceptionResolver는 이것을 500 오류가 아니라 HTTP 상태 코드 400 오류로 변경한다.

Spring 내부 오류를 어떻게 처리할지 수많은 내용이 정의되어 있다.

 

  • 코드 확인

DefaultHandlerExceptionResolver.handleTypeMismatch를 보면 다음과 같은 코드를 확인할 수 있다.

 

response.sendError(HttpServletResponse.SC_BAD_REQUEST)(400)

결국 response.sendError()를 통해서 문제를 해결한다.

 

sendError(400)를 호출했기 때문에 WAS에서 다시 오류 페이지(/error)를 내부 요청한다.

 

  • ApiExceptionController - 추가
@GetMapping("/api/default-handler-ex")
public String defaultException(@RequestParam Integer data) {
	 return "ok";
}

 

Integer data에 문자를 입력하면 내부에서 TypeMismatchException이 발생한다.

 

실행해서 결과를 확인해 보자.

 

{
     "status": 400,
     "error": "Bad Request",
     "exception":
    "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException"
    ,
     "message": "Failed to convert value of type 'java.lang.String' to required 
    type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: 
    For input string: \"hello\"",
     "path": "/api/default-handler-ex"
}

 

결과를 보면 HTTP 상태 코드가 400인 것을 확인할 수 있다.

 

지금까지 다음 ExceptionResolver들에 대해 알아보았다.

 

중간 정리해 보면 

 

ResponseStatusExceptionResolver -> HTTP 응답 코드 변경

DefaultHandlerExceptionResolver -> 스프링 내부 예외 처리

 

HTTP 상태 코드를 변경하고, 스프링 내부 예외의 상태 코드를 변경하는 기능도 알아보았다.

그런데 HandlerExceptionResolver를 직접 사용하기는 복잡하다.

 

API 오류 응답의 경우 response에 직접 데이터를 넣어야 해서 매우 불편하고 번거롭다.

ModelAndView를 반환해야 하는 것도 API에서 잘 맞지 않는다.

 

Spring은 이 문제를 해결하기 위해 @ExceptionHandler라는 매우 혁신적인 예외 처리 기능을 제공한다.

그럼 바로 ExceptionHandlerExceptionResolver에 대해 알아보자.

 


API Exception Handling - @ExceptionHandler

 

■ HTML 화면 오류 vs API 오류

 

웹 브라우저에 HTML 화면을 제공할 때는 오류가 발생하면 BasicErrorController를 사용하는 게 편하다.

 

이때는 단순히 5xx, 4xx 관련된 오류 화면을 보여주면 된다.

BasicErrorController는 이런 메커니즘을 모두 구현해 두었다.

 

그런데 API는 각 시스템마다 응답의 모양도 다르고, 스펙도 모두 다르다.

예외 상황에 단순히 오류 화면을 보여주는 것이 아니라, 예외에 따라서 각각 다른 데이터를 출력해야 할 수도 있다.

 

그리고 같은 예외라고 해도 어떤 Controller에서 발생했는가에 따라서 다른 예외 응답을 내려주어야 할 수 있다.

한마디로 매우 세밀한 제어가 필요하다.

 

앞서 이야기했지만, 예를 들어서 상품 API와 주문 API는 오류가 발생했을 때 응답의 모양이 완전히 다를 수 있다.

 

결국 지금까지 살펴본 BasicErrorController를 사용하거나 HandlerExceptionResolver를 직접 구현하는 방식으로 API 예외를 다루기는 쉽지 않다.

 

■ API 예외처리의 어려운 점

 

  • HandlerExceptionResolver를 떠올려 보면 ModelAndView를 반환해야 했다. 
    • 이것은 API 응답에는 필요하지 않다.
  • API 응답을 위해서 HttpServletResponse에 직접 응답 데이터를 넣어주었다.
    • 이것은 매우 불편하다. Spring Controller에 비유하면 마치 과거 servlet을 사용하던 시절로 돌아간 것 같다.
  • 특정 Controller에서만 발생하는 예외를 별도로 처리하기 어렵다.
    • 예를 들어서 회원을 처리하는 Controller에서 발생하는 RuntimeException 예외와 상품을 관리하는 Controller에서 발생하는 동일한 RuntimeException 예외를 서로 다른 방식으로 처리하고 싶다면 어떻게 해야 할까?

 

■ @ExceptionHandler

 

Spring은 API 예외 처리 분제를 해결하기 위해 @ExceptionHandler라는 애노테이션을 사용하는 매우 편리한 예외 처리 기능을 제공하는데,

 

이것은 바로 ExceptionHandlerExceptionResolver이다.

 

Spring은 ExceptionHandlerExceptionResolver를 기본으로 제공하고,

기본으로 제공하는 ExceptionResolver 중에 우선순위도 가장 높다.

(실무에서 API 예외 처리는 대부분 이 기능을 사용한다.)

 

예재로 알아보자.

 

  • ErrorResult
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class ErrorResult {
     private String code;
     private String message;
}

 

예외가 발생했을 때 API 응답으로 사용하는 객체를 정의했다.

 

  • ApiExceptionV2 Controller
import hello.exception.exception.UserException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@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;
     }
}

 

■ @ExceptionHandler 예외 처리 하는 방법

 

@ExceptionHandler 애노테이션을 선언하고, 해당 Controller에서 처리하고 싶은 예외를 지정해 주면 된다.

해당 Controller에서 예외가 발생하면 이 메서드가 호출된다.

 

참고로 지정한 예외 또는 그 예외의 자식 클래스는 모두 잡을 수 있다.

 

다음 예제는 IllegalArumentException 또는 그 하위 자식 클래스를 모두 처리할 수 있다.

 

@ExceptionHandler(IllegalArgumentException.class)
public ErrorResult illegalExHandle(IllegalArgumentException e) {
     log.error("[exceptionHandle] ex", e);
     return new ErrorResult("BAD", e.getMessage());
}

 

■ 우선순위

 

Spring의 우선순위는 항상 자세한 것이 우선권을 가진다.

예를 들어서 부모, 자식 클래스가 있고 다음과 같이 예외가 처리된다.

 

@ExceptionHandler(부모예외.class)
public String 부모예외처리()(부모예외 e) {}

@ExceptionHandler(자식예외.class)
public String 자식예외처리()(자식예외 e) {}

 

@ExceptionHandler에 지정한 부모 클래스는 자식 클래스까지 처리할 수 있다.

따라서 자식예외가 발생하면 부모예외처리(), 자식예외처리() 호출 대상이 된다.

그런데 둘 중 더 자세한 것이 우선권을 가지므로 자식예외처리()가 호출된다.

 

물론 부모예외가 호출되면 부모예외처리()만 호출 대상이 되므로 부모예외처리()가 호출된다.

 

■ 다양한 예외

 

다음과 같이 다양한 예외를 한 번에 처리할 수 있다.

@ExceptionHandler({AException.class, BException.class})
public String ex(Exception e) {
 	log.info("exception e", e);
}

 

■  예외 생략

 

@ExceptionHandler에 예외를 생략할 수 있다.

생략하면 메서드 파라미터의 예외가 지정된다.

@ExceptionHandler
public ResponseEntity<ErrorResult> userExHandle(UserException e) {}

 

■  파라미터와 응답

 

@ExceptionHandler에는 마치 Spring의 Controller의 파라미터 응답처럼 다양한 파라미터와 응답을 지정할 수 있다.

 

자세한 파라미터와 응답은 다음 공식 매뉴얼을 참고하자.

 

Exceptions :: Spring Framework

@Controller and @ControllerAdvice classes can have @ExceptionHandler methods to handle exceptions from controller methods, as the following example shows: @Controller public class SimpleController { // ... @ExceptionHandler public ResponseEntity handle(IOE

docs.spring.io

 

  • IllegalArgumentException 처리
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class)
public ErrorResult illegalExHandle(IllegalArgumentException e) {

     log.error("[exceptionHandle] ex", e);
     return new ErrorResult("BAD", e.getMessage());
     
}

 

// 실행 흐름

1.컨트롤러를 호출한 결과 IllegalArgumentException 예외가 컨트롤러 밖으로 던져진다.

2.예외가 발생했으로 ExceptionResolver 가 작동한다. 가장 우선순위가 높은 ExceptionHandlerExceptionResolver 가 실행된다.

3.ExceptionHandlerExceptionResolver 는 해당 컨트롤러에 IllegalArgumentException 을 처리할
수 있는 @ExceptionHandler 가 있는지 확인한다.

4.illegalExHandle() 를 실행한다. @RestController 이므로 illegalExHandle() 에도
@ResponseBody 가 적용된다. 따라서 HTTP 컨버터가 사용되고, 응답이 다음과 같은 JSON으로 반환된다.

5.@ResponseStatus(HttpStatus.BAD_REQUEST) 를 지정했으므로 HTTP 상태 코드 400으로 응답한다.

 

Postman으로 결과를 확인하면 다음과 같이 나오는 걸 확인할 수 있다.

{
 "code": "BAD",
 "message": "잘못된 입력 값"
}

 

  • UserException 처리
@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);
     
}

 

@ExceptionHandler에 예외를 지정하지 않으면 해당 메서드 파라미터 예외를 사용한다.

여기서는 UserException을 사용했다.

 

ResponseEntity를 사용해서 HTTP 메시지 바디에 직접 응답한다.

물론 HTTP 컨버터가 사용된다.

 

ResponseEntity를 사용하면 HTTP 응답 코드를 프로그래밍해서 동적으로 변경할 수 있다.

앞서 살펴본 @ResponseStatus는 애노테이션이므로 HTTP 응답 코드를 동적으로 변경할 수 없다.

 

  • Exception
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler
public ErrorResult exHandle(Exception e) {
     log.error("[exceptionHandle] ex", e);
     return new ErrorResult("EX", "내부 오류");
}

 

  • throw new RuntimeException("잘못된 사용자") 이 코드가 실행되면서, Controller 밖으로 RuntimeException이 던져진다.
  • RuntimeExceptionException의 자식 클래스이다. 따라서 이 메서드가 호출된다.
  • @ResponseStatus(HttpStatus, INTERNAL_SERVER_ERROR)로 HTTP 상태 코드를 500으로 응답한다.

API Exception Handling - @ControllerAdvice

 

@ExceptionHandler를 사용해서 예외를 깔끔하게 처리할 수 있게 되었지만,

정상 코드와 예외 처리 코드가 하나의 Controller에 섞여 있다.

 

@ControllerAdvice 또는 @RestControllerAdvice를 사용하면 둘을 분리할 수 있다.

 

  • ExControllerAdvice
import hello.exception.exception.UserException;
import hello.exception.exhandler.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class ExControllerAdvice {

     @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", "내부 오류");
         
     }
}

 

  • ApiExceptionV2Controller 코드에 있는 @ExceptionHandler 모두 제거
import hello.exception.exception.UserException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
public class ApiExceptionV2Controller {

     @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;
     }
}

 

■  @ControllerAdvice

 

  • @ControllerAdvice는 대상으로 지정한 여러 Controller에 @ExceptionHandler, @InitBinder 기능을 부여해 주는 역할을 한다.
  • @ControllerAdvice에 대상을 지정하지 않으면 모든 Controller에 적용된다.(글로벌 적용)
  • @RestControllerAdvice@ControllerAdvice와 같고, @ResponseBody가 추가되어 있다.
  • @Controller, @RestController의 차이와 같다.

 

 

  • 대상 컨트롤러 지정 방법
// 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 {}

 

위 소스는 스프링 공식 문서 예제에서 보는 것처럼 특정 애노테이션이 있는 Controller를 지정할 수 있고,

특정 패키지를 직접 지정할 수도 있다. 

 

패키지 지정의 경우 해당 패키지와 그 하위에 있는 Controller가 대상이 된다.

그리고 특정 클래스를 지정할 수 있고, 대상 Controller 지정을 생략하면 모든 Controller에 적용된다.

 

자세한 사항은 공식 문서를 확인해 보자.

 

Controller Advice :: Spring Framework

@ExceptionHandler, @InitBinder, and @ModelAttribute methods apply only to the @Controller class, or class hierarchy, in which they are declared. If, instead, they are declared in an @ControllerAdvice or @RestControllerAdvice class, then they apply to any c

docs.spring.io


마치며

 

@ExceptionHandler@ControllerAdvice를 조합하면 예외를 깔끔하게 해결할 수 있다.

 

지금까지 API Exception Handling 포스팅으로 알아봤습니다.

다음 포스팅에서 뵙겠습니다.

 

위 포스팅은 김영한님의 Spring MVC 2편 - 백엔드 웹 개발 활용  강의를 참고했습니다.

 

스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 강의 - 인프런

웹 애플리케이션 개발에 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. MVC 2편에서는 MVC 1편의 핵심 원리와 구조 위에 실무 웹 개발에 필요한 모든 활용 기술들을 학습할 수 있

www.inflearn.com

 

728x90