Spring MVC(4) @ExceptionHandler과 @ControllerAdvice를 이용한 API 예외처리

오잉·2023년 4월 19일
0

SPRING

목록 보기
11/15

API는 각 시스템 마다 응답의 모양도 다르고, 스펙도 모두 다르다.
예외 상황에 단순히 오류 화면을 보여주는 것이 아니라, 예외에 따라서 각각 다른 데이터를 출력해야 할 수도 있다.
그리고 같은 예외라고 해도 어떤 컨트롤러에서 발생했는가에 따라서 다른 예외 응답을 내려주어야 할 수 있다.
한마디로 API에 대한 예외처리는 매우 세밀한 제어가 필요하다.

각 컨트롤러마다 발생하는 예외를 별도로 처리하기 위해 스프링은 @ExceptionHandler라는 애노테이션을 만들었다.

1. @ExceptionHandler

0) 기본 사용법

@RestController
public class ApiExceptionV2Controller {

	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(IllegalArgumentException.class)
    public ErrorResult illegalExHandle(IllegalArgumentException e) {
        return new ErrorResult("BAD", e.getMessage());
    }
    
    @ExceptionHandler
    public ResponseEntity<ErrorResult> userExHandle(UserException 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) {
    	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);
      }
}
  • @ExceptionHandler 애노테이션을 선언하고, 해당 컨트롤러에서 처리하고 싶은 예외를 지정해주면 된다.
  • 해당 컨트롤러에서 예외가 발생하면 이 메서드가 호출된다.
  • 참고로 지정한 예외 또는 그 예외의 자식 클래스는 모두 잡을 수 있다.

1) 우선순위

스프링의 우선순위는 항상 자세한 것이 우선권을 가진다.
예를 들어서 부모예외와 자식예외를 잡는 @ExceptionHandler가 각각 존재할 경우,
자식예외가 발생하면 자식예외처리가 호출된다.

2) 다양한 예외

다양한 예외를 한번에 처리할 수 있다.

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

3) 예외 생략

@ExceptionHandler 에 예외를 생략할 수 있다.
생략하면 메서드 파라미터의 예외가 지정된다.

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

4) 기타

다음과 같이 ModelAndView 를 사용해서 오류 화면(HTML)을 응답하는데 사용할 수도 있다.

@ExceptionHandler(ViewException.class)
public ModelAndView ex(ViewException e) {
      log.info("exception e", e);
      return new ModelAndView("error");
}

2. @ControllerAdvice

@ControllerAdvice 없이 @ExceptionHandler만 사용했을 때

@RestController
public class ApiExceptionV2Controller {

	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(IllegalArgumentException.class)
    public ErrorResult illegalExHandle(IllegalArgumentException e) {
        return new ErrorResult("BAD", e.getMessage());
    }
    
    @ExceptionHandler
    public ResponseEntity<ErrorResult> userExHandle(UserException 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) {
    	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);
      }
}

@ExceptionHandler 를 사용해서 예외를 깔끔하게 처리할 수 있게 되었지만, 정상 코드와 예외 처리 코드가 하나의 컨트롤러에 섞여 있다.

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

@ControllerAdvice 적용

@RestControllerAdvice
public class ExControllerAdvice {

	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(IllegalArgumentException.class)
    public ErrorResult illegalExHandle(IllegalArgumentException e) {
        return new ErrorResult("BAD", e.getMessage());
    }
    
    @ExceptionHandler
    public ResponseEntity<ErrorResult> userExHandle(UserException 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) {
    	return new ErrorResult("EX", "내부 오류");	
    }
}
@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);
      }
}
  • @ControllerAdvice 는 대상으로 지정한 여러 컨트롤러에 @ExceptionHandler , @InitBinder 기능을 부여해주는 역할을 한다.
  • @RestControllerAdvice 는 @ControllerAdvice 와 같고, @ResponseBody 가 추가되어 있다. @Controller , @RestController 의 차이와 같다.

@ControllerAdvice 대상 지정

  // 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 {}

참고) 대상을 지정하지 않으면 모든 컨트롤러에 적용된다. (글로벌 적용)

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


인프런 김영한님 스프링 MVC2의 [섹션9. API예외처리]
스프링 공식문서 Exceptions

profile
오잉이라네 오잉이라네 오잉이라네 ~

0개의 댓글