|
| 1 | +package com.back.global.globalExceptionHandler; |
| 2 | + |
| 3 | + |
| 4 | +import com.back.global.exception.ServiceException; |
| 5 | +import com.back.global.rsData.RsData; |
| 6 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 7 | +import jakarta.validation.ConstraintViolationException; |
| 8 | +import org.springframework.http.HttpStatus; |
| 9 | +import org.springframework.http.ResponseEntity; |
| 10 | +import org.springframework.http.converter.HttpMessageNotReadableException; |
| 11 | +import org.springframework.validation.FieldError; |
| 12 | +import org.springframework.web.bind.MethodArgumentNotValidException; |
| 13 | +import org.springframework.web.bind.MissingRequestHeaderException; |
| 14 | +import org.springframework.web.bind.annotation.ExceptionHandler; |
| 15 | +import org.springframework.web.bind.annotation.RestControllerAdvice; |
| 16 | + |
| 17 | +import java.io.IOException; |
| 18 | +import java.util.Comparator; |
| 19 | +import java.util.NoSuchElementException; |
| 20 | +import java.util.stream.Collectors; |
| 21 | + |
| 22 | +import static org.springframework.http.HttpStatus.BAD_REQUEST; |
| 23 | +import static org.springframework.http.HttpStatus.NOT_FOUND; |
| 24 | + |
| 25 | +/** |
| 26 | + * 글로벌 예외 핸들러 클래스 |
| 27 | + * 각 예외에 대한 적절한 HTTP 상태 코드와 메시지를 포함한 응답 반환 |
| 28 | + * 400: Bad Request |
| 29 | + * 404: Not Found |
| 30 | + * 500: Internal Server Error |
| 31 | + */ |
| 32 | + |
| 33 | +@RestControllerAdvice |
| 34 | +public class GlobalExceptionHandler { |
| 35 | + |
| 36 | + // ServiceException: 서비스 계층에서 발생하는 커스텀 예외 |
| 37 | + @ExceptionHandler(ServiceException.class) |
| 38 | + public ResponseEntity<RsData<Void>> handle(ServiceException ex) { |
| 39 | + RsData<Void> rsData = ex.getRsData(); |
| 40 | + int statusCode = rsData.code(); |
| 41 | + |
| 42 | + HttpStatus status = HttpStatus.resolve(statusCode); |
| 43 | + if( status == null) { |
| 44 | + status = HttpStatus.INTERNAL_SERVER_ERROR; // 기본값 설정 |
| 45 | + } |
| 46 | + return ResponseEntity.status(status).body(rsData); |
| 47 | + |
| 48 | + } |
| 49 | + |
| 50 | + // NoSuchElementException: 데이터 없을떄 예외 |
| 51 | + @ExceptionHandler(NoSuchElementException.class) |
| 52 | + public ResponseEntity<RsData<Void>> handle(NoSuchElementException ex) { |
| 53 | + return new ResponseEntity<>( |
| 54 | + RsData.of( |
| 55 | + 404, |
| 56 | + "해당 데이터가 존재하지 않습니다" |
| 57 | + ), |
| 58 | + NOT_FOUND |
| 59 | + ); |
| 60 | + } |
| 61 | + |
| 62 | + //ConstraintViolationException: 제약 조건(@NotNull, @Size 등)을 어겼을 때 발생예외 |
| 63 | + @ExceptionHandler(ConstraintViolationException.class) |
| 64 | + public ResponseEntity<RsData<Void>> handle(ConstraintViolationException ex) { |
| 65 | + //메세지 형식 : <필드명>-<검증어노테이션명>-<검증실패메시지> |
| 66 | + String message = ex.getConstraintViolations() |
| 67 | + .stream() |
| 68 | + .map( |
| 69 | + violation -> { |
| 70 | + String path = violation.getPropertyPath().toString(); |
| 71 | + String field = path.contains(".") ? path.split("\\.",2)[1]: path; |
| 72 | + String[] messageTemplateBits = violation.getMessageTemplate() |
| 73 | + .split("\\."); |
| 74 | + String code = messageTemplateBits.length >= 2 |
| 75 | + ? messageTemplateBits[messageTemplateBits.length -2] : "Unknown"; |
| 76 | + |
| 77 | + String _message = violation.getMessage(); |
| 78 | + |
| 79 | + return "%s-%s-%s".formatted(field, code, _message); |
| 80 | + }) |
| 81 | + .sorted() |
| 82 | + .collect(Collectors.joining("\n")); |
| 83 | + |
| 84 | + return new ResponseEntity<>( |
| 85 | + RsData.of( |
| 86 | + 400, |
| 87 | + message |
| 88 | + ), |
| 89 | + BAD_REQUEST |
| 90 | + ); |
| 91 | + } |
| 92 | + |
| 93 | + |
| 94 | + // MethodArgumentNotValidException: @Valid 어노테이션을 사용한 유효성 검사 실패시 발생하는 예외 |
| 95 | + @ExceptionHandler(MethodArgumentNotValidException.class) |
| 96 | + public ResponseEntity<RsData<Void>> handle(MethodArgumentNotValidException ex) { |
| 97 | + //메세지 형식 : <필드명>-<검증어노테이션명>-<검증실패메시지> |
| 98 | + String message = ex.getBindingResult() |
| 99 | + .getAllErrors() |
| 100 | + .stream() |
| 101 | + .filter(error -> error instanceof FieldError) |
| 102 | + .map(error -> (FieldError) error) |
| 103 | + .map(error -> error.getField() + "-" + error.getCode() + "-" + error.getDefaultMessage()) |
| 104 | + .sorted(Comparator.comparing(String::toString)) |
| 105 | + .collect(Collectors.joining("\n")); |
| 106 | + |
| 107 | + return new ResponseEntity<>( |
| 108 | + RsData.of( |
| 109 | + 400, |
| 110 | + message |
| 111 | + ) , |
| 112 | + BAD_REQUEST |
| 113 | + ); |
| 114 | + } |
| 115 | + |
| 116 | + // HttpMessageNotReadableException : 요청 본문이 올바르지 않을 때 발생하는 예외 |
| 117 | + @ExceptionHandler(HttpMessageNotReadableException.class) |
| 118 | + public ResponseEntity<RsData<Void>> handle(HttpMessageNotReadableException ex) { |
| 119 | + return new ResponseEntity<>( |
| 120 | + RsData.of( |
| 121 | + 400, |
| 122 | + "요청 본문이 올바르지 않습니다." |
| 123 | + ), |
| 124 | + BAD_REQUEST |
| 125 | + ); |
| 126 | + } |
| 127 | + |
| 128 | + // MissingRequestHeaderException : 필수 요청 헤더가 누락되었을 때 발생하는 예외 |
| 129 | + @ExceptionHandler(MissingRequestHeaderException.class) |
| 130 | + public ResponseEntity<RsData<Void>> handle(MissingRequestHeaderException ex) { |
| 131 | + // 메세지 형식 : <필드명>-<검증어노테이션명>-<검증실패메시지> |
| 132 | + String message = "%s-%s-%s".formatted( |
| 133 | + ex.getHeaderName(), |
| 134 | + "NotBlank", |
| 135 | + ex.getLocalizedMessage() |
| 136 | + ); |
| 137 | + |
| 138 | + return new ResponseEntity<>( |
| 139 | + RsData.of( |
| 140 | + 400, |
| 141 | + message |
| 142 | + ), |
| 143 | + BAD_REQUEST |
| 144 | + ); |
| 145 | + } |
| 146 | + |
| 147 | + @ExceptionHandler(JsonProcessingException.class) |
| 148 | + public ResponseEntity<RsData<Void>> handleJsonProcessingException(JsonProcessingException e) { |
| 149 | + return ResponseEntity.badRequest() |
| 150 | + .body(RsData.of(400, "JSON 파싱 오류가 발생했습니다.", null)); |
| 151 | + } |
| 152 | + |
| 153 | + @ExceptionHandler(IOException.class) |
| 154 | + public ResponseEntity<RsData<Void>> handleIOException(IOException e) { |
| 155 | + return ResponseEntity.internalServerError() |
| 156 | + .body(RsData.of(500, "서버 내부 오류가 발생했습니다.", null)); |
| 157 | + } |
| 158 | + |
| 159 | +} |
0 commit comments