[Spring Boot] Global Exception 에러 처리

개인프로젝트를 진행중 

회원가입 개발중

1. 아이디가 존재하지 않습니다.

2. 비밀번호가 존재하지 않습니다.

 

이러한 기능등을 한번에 관리하고싶어서 서치를 해봤다.

Global Exception 에러처리 방식이 존재하는것같다

 

@RestControllerAdvice

Spring Boot에서 전역 예외 처리를 제공하기 위한 애너테이션.

주로 컨트롤러에서 발생하는 예외를 잡아 공통된 에러 응답을 처리하거나 로깅을 수행하는데 주로 사용함

 

GlobalExceptionhandler.java

package dev.memory.tododoit.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    // ErrorCode내의 에러
    @ExceptionHandler(CustomException.class)
    protected ResponseEntity<ErrorResponse> handleCustomException(CustomException e) {
        log.error("CustomException: {}", e.getMessage(), e);

        // ErrorResponse 생성 및 반환
        ErrorResponse errorResponse = ErrorResponse.of(e.getErrorCode());

        return ResponseEntity
                .status(e.getErrorCode().getHttpStatus())
                .body(errorResponse);
    }
}

 

ErrorResponse.java

package dev.memory.tododoit.exception;

import lombok.Getter;

import java.time.LocalDateTime;

@Getter
public class ErrorResponse {
    private final LocalDateTime timestamp;  // 오류발생 시간
    private final int statusCode;           // 오류 상태코드
    private final String errorCode;         // 오류코드
    private final String message;           // 반환 메세지

    public ErrorResponse(ErrorCode errorCode) {
        this.timestamp = LocalDateTime.now();
        this.statusCode = errorCode.getHttpStatus().value();
        this.errorCode = errorCode.getErrorCode();
        this.message = errorCode.getMessage();
    }

    // ErrorCode를 기반으로 ErrorResponse 생성
    public static ErrorResponse of(ErrorCode errorCode) {
        return new ErrorResponse(errorCode);
    }
}

 

ErrorCode.java

package dev.memory.tododoit.exception;

import lombok.Getter;
import org.springframework.http.HttpStatus;

@Getter
public enum ErrorCode {

    /**
     * testCode 추후 추가 예정
     */
    NOT_FUN(HttpStatus.NOT_FOUND, "T-001", "테스트코드입니다 추후삭제예정.");

    private final HttpStatus httpStatus;
    private final String errorCode;
    private final String message;

    ErrorCode(HttpStatus httpStatus, String errorCode, String message) {
        this.httpStatus = httpStatus;
        this.errorCode = errorCode;
        this.message = message;
    }

}

 

CustomException.java

package dev.memory.tododoit.exception;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class CustomException extends RuntimeException {
    private final ErrorCode errorCode;
}
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유