예외 처리 세팅

terranking·2024년 1월 18일
0

Spring

목록 보기
4/7
post-thumbnail

springboot 3.2.1

1. OutsourcingException

@Getter
public abstract class OutsourcingException extends RuntimeException {
    private final Map<String, String> validation = new HashMap<>();

    public OutsourcingException(String message) {
        super(message);
    }

    public abstract int getStatusCode();

    public void addValidation(String filedName, String message) {
        validation.put(filedName, message);
    }
}

2. ErrorResponse

@Getter
public class ErrorResponse {
    private final String code;
    private final String message;
    private final Map<String, String> validation;

    @Builder
    public ErrorResponse(String code, String message, Map<String, String> validation) {
        this.code = code;
        this.message = message;
        this.validation = (validation != null) ? validation : new HashMap<>();
    }

    public void addValidation(String fieldName, String errorMessage) {
        this.validation.put(fieldName, errorMessage);
    }
}

3. ExceptionController

@RestControllerAdvice
public class ExceptionController {

    @ExceptionHandler(OutsourcingException.class)
    public ResponseEntity<ErrorResponse> outsourcingException(OutsourcingException e) {
        int statusCode = e.getStatusCode();

        ErrorResponse body = ErrorResponse.builder()
                .code(String.valueOf(statusCode))
                .message(e.getMessage())
                .validation(e.getValidation())
                .build();

        return ResponseEntity.status(statusCode)
                .body(body);
    }
}
profile
back-end newbie🌱

0개의 댓글