모든 리소스를 대상으로 예외 처리 구현하기

Soo·2024년 3월 24일

저번 기록에서는 Not Found 에러처리에 대해서 알아보았습니다.

애플리케이션을 만들다 보면 여러 에러를 만나게 되어있습니다.

그만큼 에러를 처리하는 과정은 매우 중요합니다.

이번 기록에서는 예외 발생 시 반환하는 응답의 구조를 바꿔보려고 합니다.

src/main/java/study/rest/webservices/restfulwebservices/exception예외처리 구조에 대한 클래스를 생성합니다.

ErrorDetails

  • 예외 발생 시간
  • 예외 메세지
  • 상세 내용
package study.rest.webservices.restfulwebservices.exception;

import java.time.LocalDate;

public class ErrorDetails {
    private LocalDate timestamp;
    private String message;
    private String details;

    public ErrorDetails(LocalDate timestamp, String message, String details) {
        this.timestamp = timestamp;
        this.message = message;
        this.details = details;
    }

    public LocalDate getTimestamp() {
        return timestamp;
    }

    public String getMessage() {
        return message;
    }

    public String getDetails() {
        return details;
    }
}

ErrorDetails와 동일한 패키지에 실제 예외를 처리하는 클래스를 생성합니다.

CustomizedResponseEntityExceptionHandler

  • 잘못된 요청을 하는 경우 NotFound 에러를 발생하겠습니다.
package study.rest.webservices.restfulwebservices.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import study.rest.webservices.restfulwebservices.user.UserNotFoundException;

import java.time.LocalDateTime;

@ControllerAdvice
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public final ResponseEntity<ErrorDetails> handleAllException(Exception ex, WebRequest request) throws Exception {
        ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(), ex.getMessage(),
                request.getDescription(false));

        return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(UserNotFoundException.class)
    public final ResponseEntity<ErrorDetails> handleUserNotFoundException(Exception ex, WebRequest request) throws Exception {
        ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(), ex.getMessage(),
                request.getDescription(false));

        return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
    }

}

@ControllerAdvice를 사용하면 모든 컨트롤러에서 발생하는 예외를 한 곳에서 처리할 수 있어서 코드의 재사용성을 높이고 중복을 줄일 수 있습니다.

@ExceptionHandler를 통해 어떤 예외가 발생할때 특정 메소드를 실행할지 지정합니다.

0개의 댓글