Spring 예외 만들기&처리하기

이재용·2025년 1월 1일
0
  1. 예외 만들기
  2. @RestControllerAdvice
  3. @ExceptionHandler
  4. @ResponseStatus

BoardException

public abstract class BoardException extends RuntimeException{  
  
    public BoardException(String message) {  
        super(message);  
    }  
  
    public BoardException(String message, Throwable cause) {  
        super(message, cause);  
    }  
  
    public abstract int getStatusCode();  
}

PostNotFound

public class PostNotFound extends BoardException {  
    private static final String MESSAGE = "존재하지 않는 글입니다";  
  
    public PostNotFound() {  
        super(MESSAGE);  
    }  
  
    public PostNotFound( Throwable cause) {  
        super(MESSAGE, cause);  
    }  
  
    @Override  
    public int getStatusCode() {  
        return 404;  
    }  
}

ExceptionController

@ResponseStatus(HttpStatus.BAD_REQUEST)  
@ExceptionHandler(MethodArgumentNotValidException.class)  
public ErrorResponse exceptionHandler(MethodArgumentNotValidException e) {  
    ErrorResponse response = ErrorResponse.builder()  
            .code("400")  
            .message("잘못된 요청입니다")  
            .build();  
  
    for(FieldError fieldError : e.getBindingResult().getFieldErrors()) {  
        response.addValidation(fieldError.getField(), fieldError.getDefaultMessage());  
    }  
    return response;  
}

@ExceptionHandler(BoardException.class)  
public ResponseEntity<ErrorResponse> exceptionHandler(BoardException e) {  
    int statusCode = e.getStatusCode();  
  
    ErrorResponse body = ErrorResponse.builder()  
            .code(String.valueOf(statusCode))  
            .message(e.getMessage())  
            .build();  
  
    return ResponseEntity.status(statusCode)  
            .body(body);  
}

@ExceptionHandler

스프링은 API 예외 처리 문제를 해결하기 위해 @ExceptionHandler라는 애노테이션을 사용하는 편리한 예외 처리 기능을 제공
@ExceptionHandler 선언하고, 해당 컨트롤러에서 처리하고 싶은 예외를 지정해주면 된다. 해당 컨트롤러에서 예외가 발생하면 이 메서드가 호출된다. 참고로 지정한 예외 또는 그 예외의 자식 클래스는 모두 잡을 수 있다.

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

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class) <- IllegalArgumentException 또는 그 하위 자식 클래스를 모두 처리할 수 있다.
public ErrorResult illegalExHandle(IllegalArgumentException e) {
	log.error("[exceptionHandle] ex", e);
	return new ErrorResult("BAD", e.getMessage());
}

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

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

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

@ExceptionHandler 
public ResponseEntity userExHandle(UserException e) {}

0개의 댓글