|
| 1 | +package com.ODG.ODG_back.exception; |
| 2 | + |
| 3 | +import com.ODG.ODG_back.dto.exception.ErrorResponse; |
| 4 | +import com.ODG.ODG_back.exception.custom.BadRequestException; |
| 5 | +import com.ODG.ODG_back.exception.custom.ExternalApiException; |
| 6 | +import com.ODG.ODG_back.exception.custom.NotFoundException; |
| 7 | +import com.ODG.ODG_back.exception.custom.UnauthorizedException; |
| 8 | +import org.springframework.http.HttpStatus; |
| 9 | +import org.springframework.http.ResponseEntity; |
| 10 | +import org.springframework.web.bind.annotation.ExceptionHandler; |
| 11 | +import org.springframework.web.bind.annotation.RestControllerAdvice; |
| 12 | + |
| 13 | +@RestControllerAdvice |
| 14 | +public class GlobalExceptionHandler { |
| 15 | + |
| 16 | + |
| 17 | + // 404 Not Found |
| 18 | + @ExceptionHandler(NotFoundException.class) |
| 19 | + public ResponseEntity<ErrorResponse> handlerNotFoundException(NotFoundException e) { |
| 20 | + return buildResponse(e.getErrorCode(), HttpStatus.NOT_FOUND); |
| 21 | + } |
| 22 | + |
| 23 | + // 400 Bad Request |
| 24 | + @ExceptionHandler(BadRequestException.class) |
| 25 | + public ResponseEntity<ErrorResponse> handlerBadRequestException(BadRequestException e) { |
| 26 | + return buildResponse(e.getErrorCode(), HttpStatus.BAD_REQUEST); |
| 27 | + } |
| 28 | + |
| 29 | + // 401 Unauthorized |
| 30 | + @ExceptionHandler(UnauthorizedException.class) |
| 31 | + public ResponseEntity<ErrorResponse> handlerUnauthorizedException(UnauthorizedException e) { |
| 32 | + return buildResponse(e.getErrorCode(), HttpStatus.UNAUTHORIZED); |
| 33 | + } |
| 34 | + |
| 35 | + // 500 Internal Server Error |
| 36 | + @ExceptionHandler(RuntimeException.class) |
| 37 | + public ResponseEntity<ErrorResponse> handlerRuntimeException(RuntimeException e) { |
| 38 | + ErrorCode errorCode = ErrorCode.INTERNAL_SERVER_ERROR; |
| 39 | + ErrorResponse response = new ErrorResponse(errorCode.getCode(), errorCode.getMessage()); |
| 40 | + return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR); |
| 41 | + } |
| 42 | + |
| 43 | + // 502, 503 External Error |
| 44 | + @ExceptionHandler(ExternalApiException.class) |
| 45 | + public ResponseEntity<ErrorResponse> handlerExternalApiException(ExternalApiException e) { |
| 46 | + return buildResponse(e.getErrorCode(), HttpStatus.valueOf(Integer.parseInt(e.getErrorCode().getCode()))); |
| 47 | + } |
| 48 | + |
| 49 | + private ResponseEntity<ErrorResponse> buildResponse(ErrorCode errorCode, HttpStatus status) { |
| 50 | + return new ResponseEntity<>(new ErrorResponse(errorCode.getCode(), errorCode.getMessage()), status); |
| 51 | + } |
| 52 | +} |
0 commit comments