|
| 1 | +package com.f_lab.la_planete.controller; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.annotation.JsonProperty; |
| 4 | +import io.swagger.v3.oas.annotations.Hidden; |
| 5 | +import jakarta.persistence.PessimisticLockException; |
| 6 | +import lombok.AllArgsConstructor; |
| 7 | +import lombok.Getter; |
| 8 | +import lombok.extern.slf4j.Slf4j; |
| 9 | +import org.hibernate.exception.LockTimeoutException; |
| 10 | +import org.springframework.http.HttpStatus; |
| 11 | +import org.springframework.http.ResponseEntity; |
| 12 | +import org.springframework.orm.jpa.JpaSystemException; |
| 13 | +import org.springframework.transaction.TransactionSystemException; |
| 14 | +import org.springframework.web.ErrorResponse; |
| 15 | +import org.springframework.web.bind.annotation.ExceptionHandler; |
| 16 | +import org.springframework.web.bind.annotation.RestControllerAdvice; |
| 17 | + |
| 18 | +@Slf4j |
| 19 | +@Hidden |
| 20 | +@RestControllerAdvice |
| 21 | +public class GlobalExceptionHandler { |
| 22 | + |
| 23 | + @ExceptionHandler(IllegalStateException.class) |
| 24 | + public ResponseEntity<ErrorResponse> handleIllegalStateException(IllegalStateException e) { |
| 25 | + return ResponseEntity |
| 26 | + .status(HttpStatus.CONFLICT) |
| 27 | + .body(ErrorResponse.of(e.getMessage(), HttpStatus.CONFLICT.value())); |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * 데이터베이스 관련 예외 (e.g. 주로 락을 얻는 대기시간이 오래되어서 요청을 반환할 때) |
| 32 | + */ |
| 33 | + @ExceptionHandler(JpaSystemException.class) |
| 34 | + public ResponseEntity<ErrorResponse> handleJpaSystemException(JpaSystemException e) { |
| 35 | + log.error("JpaSystemException occurred", e); |
| 36 | + return ResponseEntity |
| 37 | + .status(HttpStatus.SERVICE_UNAVAILABLE) |
| 38 | + .body(ErrorResponse.of( |
| 39 | + "현재 너무 많은 요청을 처리하고 있습니다. 다시 시도해주세요", |
| 40 | + HttpStatus.SERVICE_UNAVAILABLE.value())); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * 어플리케이션에서 처리하지 못한 다른 모든 예외 |
| 45 | + */ |
| 46 | + @ExceptionHandler(Exception.class) |
| 47 | + public ResponseEntity<ErrorResponse> handleGenericException(Exception e) { |
| 48 | + log.error("Unexpected Error occurred. Requires Potential Handling", e); |
| 49 | + return ResponseEntity |
| 50 | + .status(HttpStatus.INTERNAL_SERVER_ERROR) |
| 51 | + .body(ErrorResponse.of( |
| 52 | + "알 수 없는 오류가 발생했습니다. 다시 시도해주세요", |
| 53 | + HttpStatus.INTERNAL_SERVER_ERROR.value())); |
| 54 | + } |
| 55 | + |
| 56 | + @Getter |
| 57 | + @AllArgsConstructor |
| 58 | + static class ErrorResponse { |
| 59 | + private String message; |
| 60 | + |
| 61 | + @JsonProperty("status_code") |
| 62 | + private int statusCode; |
| 63 | + |
| 64 | + public static ErrorResponse of(String message, int statusCode) { |
| 65 | + return new ErrorResponse(message, statusCode); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments