Springboot

[Springboot] Handler, @ExceptionHandler, @ControllerAdvice

KJihun 2023. 7. 11. 00:31
728x90

Handler

  • 클라이언트로부터의 요청을 처리하고, 해당 요청에 대한 적절한 작업을 수행하는 역할
  • @Controller와 @RestController를 사용하여 정의한다.
  • 핸들러는 특정 URL에 매핑되고 해당 URL로 요청이 들어오면 실행된다.

 


 

@ExceptionHandler

@ExceptionHandler: @ExceptionHandler를 사용한 handler에서 발생하는 모든 예외를 하나의 메서드로 처리할 수 있다.

 

아래는 PostController에서 NullPointerException발생 시 nullex 메서드를 호출하는 코드이다.

@RestController
public class PostController {
    ...
    ...
    @ExceptionHandler(NullPointerException.class)
    public Object nullex(Exception e) {
        System.err.println(e.getClass());
        return "PostService";
    }
}

 

 

  • 두 개 이상의 예외도 등록이 가능하다.@ExceptionHandler({ Exception1.class, Exception2.class ... })
  • @ExceptionHandler를 등록한 Controller에만 적용된다

 


 

@ControllerAdvice

 

@ControllerAdvice: 모든 handler에서 발생할 수 있는 예외를 처리해준다

@RestControllerAdvice와 @ControllerAdvice가 존재한다.

 

 


 

@RestControllerAdvice

 

@ControllerAdvice와 동일하나 @ResponseBody를 통해 객체를 리턴할 수도 있다.

ViewResolver를 통해서 예외 처리 페이지로 리다이렉트 시키려면 @ControllerAdvice만 써도 되고, API서버여서 에러 응답으로 객체를 리턴해야한다면 @RestControllerAdvice를 사용하면 된다.

 

작성 예시

@Getter
@AllArgsConstructor
public class RestApiException {
    private String errorMessage;
    private int statusCode;
}
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({IllegalArgumentException.class})
    public ResponseEntity<RestApiException> illegalArgumentExceptionHandler(IllegalArgumentException ex) {
        RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
        return new ResponseEntity<>(
                // HTTP body
                restApiException,
                // HTTP status code
                HttpStatus.BAD_REQUEST
        );
    }

IllergalArgumentException 예외 발생 시 RestApiExcetion타입인 errorMessage와 StatusCode를 반환한한다.

 

'Springboot' 카테고리의 다른 글

[Springboot] DAO, DTO, VO  (0) 2023.07.18
[Springboot] CORS란?  (2) 2023.07.15
[Springboot] 관계 매핑(ORM; Object Relational Mapping) N:M  (0) 2023.07.07
[Springboot] Security  (0) 2023.07.01
[Springboot] Filter와 Spring Security  (0) 2023.06.30