@ControllerAdvice으로 @ExceptionHandler 전역 에러 핸들러 만들기

728x90

@ControllerAdvice

@RestControllerAdvice

를 사용하여 @ExceptionHandler 을 전역으로 설정

 

컨트롤러에서 사용되는 공통 기능들을 모듈화하기 위한 어노테이션으로, 

 

 

@InitBinder @ModelAttribute @ExceptionHandler 세 가지 어노테이션을 지원합니다.

 

이 중 @ExceptionHandler 를 사용해 보았습니다.

@Slf4j
@RestControllerAdvice
public class ExceptionHandlerAdvice {

    /*
    400 Bad Request - 클라이언트가 유효하지 않은 요청을 보낸 경우
    401 Unauthorized - 해당 서버에 클라이언트 인증이 실패한 경우
    403 Forbidden - 클라이언트가 인증은 됐지만 요청한 자원에 대한 권한은 없는 경우
    404 Not Found - 요청한 자원이 존재하지 않는 경우
    412 Precondition Failed - Request Header 필드 중 한 개 이상의 값이 잘못 된
    */

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ErrorResult notReadExHandler(Exception e){
        log.error("ex", e);
        return new ErrorResult("유효하지 않은 요청", e.getMessage());
    }

    @ResponseStatus(HttpStatus.PRECONDITION_FAILED)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public ErrorResult notMediaTypeNotSupport(Exception e){
        log.error("ex", e);
        return new ErrorResult("JSON 타입만 지원합니다.", e.getMessage());
    }

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler
    public ErrorResult exHandler(Exception e){
        log.error("ex", e);
        return new ErrorResult("EX", e.getMessage());
    }
}

실제로 json이 아닌 text로 요청을 보내보면 지원하지 않는 MediaType로 에러가 발생


@Controller -> @ControllerAdvice

@RestController -> @RestControllerAdvice

를 사용하면 되겠습니다.

 

@RestControllerAdvice("패키지")
public class ExceptionHandlerAdvice {

  ...
}

패키지를 지정해서 해당 패키지로만 적용할 수도 있습니다.

반응형