개발/spring boot

에러 처리

Eprld 2025. 1. 22. 15:45

 

페이지 상태코드가 발생할 시 함께 에러메시지를 제공하는 코드

@Getter
public enum ErrorCode {

    INVALID_INPUT_VALUE(400,"invalid input value"),
    NOT_FOUND(404, "not found data"),
    INTERNAL_ERROR(500, "unexpected error");

    private final Integer code;
    private final String message;

    ErrorCode(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}

 

사전정의 된 ErrorCode로 예외가 발생 시 적절한 로그를 남기게 도와주는 코드 

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public Response<Void> handleIllegalArgumentException(IllegalArgumentException e) {
        log.error(e.getMessage());
        return Response.error(ErrorCode.INVALID_INPUT_VALUE);
    }

    @ExceptionHandler(Exception.class)
    public Response<Void> handleException(Exception e) {
        return Response.error(ErrorCode.INTERNAL_ERROR);
    }
}

 

정상응답, 에러응답

public record Response<T>(Integer code, String msg, T value) {

    public static <T> Response<T> ok(T value) {
        return new Response<T>(200, "OK", value);
    }

    public static <T> Response<T> error(ErrorCode errorCode) {
        return new Response<>(errorCode.getCode(), errorCode.getMessage(), null);
    }
}

 

'개발 > spring boot' 카테고리의 다른 글

post 글쓰기  (0) 2025.01.27
postman으로 데이터 생성 및 조회  (0) 2025.01.22
querydsl  (0) 2025.01.19
querydsl  (0) 2025.01.17
테이블 생성  (0) 2025.01.17