본문 바로가기
Spring Boot

Spring 예외 처리 GlobalExceptionHandler 사용 이유

by 코딩diary 2025. 2. 27.

스프링으로 CRUD를 만들 때 GlobalExceptionHandler를 만든 이유

 

컨트롤러 안에서 예외를 직접 처리하지 않고 전역적으로 관리하기 위함.

 

@ControllerAdvice 없이 컨트롤러에서 예외를 처리하면 모든 메서드마다 try-catch가 들어가서 코드가 길어진다.

@RestController
@RequestMapping("/users")
public class UserController {
    
    @PostMapping
    public ResponseEntity<?> createUser(@RequestBody UserRequest request) {
        try {
            User user = userService.createUser(request);
            return ResponseEntity.ok(user);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("잘못된 요청");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("서버 오류");
        }
    }
}

그래서 GlobalExceptionHandler를 만들어서 중복 제거.

 

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
    }

    @ExceptionHandler(NoSuchElementException.class)
    public ResponseEntity<String> handleNoSuchElement(NoSuchElementException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("해당 데이터를 찾을 수 없습니다.");
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGlobalException(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("서버 오류 발생");
    }
}

자주 발생하는 예외를 한곳에서 처리해서 컨트롤러 코드를 깔끔하게 만들 수 있다.

 

 

CRUD에서 발생하는 예외를 한 곳에서 관리하고, 컨트롤러 코드를 간결하게 유지하기 위해 GlobalExceptionHandler를 만들었다.

- 컨트롤러에서 try-catch 사용할 필요 X

- 예외를 한 곳에서 처리하여 유지보수 O

- 클라이언트에게 일관된 에러 응답을 줄 수 있다.