스프링 예외처리 실습

김성수·2022년 11월 28일
0

트러블슈팅

목록 보기
3/12

global 처리

@ExceptionHandler
    public ResponseEntity handleBusinessLogicException(BusinessLogicException e) {
        final ErrorResponse response = ErrorResponse.of(e.getExceptionCode());

        // TODO GlobalExceptionAdvice 기능 추가 1
        return new ResponseEntity<>(response ,HttpStatus.valueOf(e.getExceptionCode()
                .getStatus()));
    }

    // TODO GlobalExceptionAdvice 기능 추가 2
    @ExceptionHandler
    public ResponseEntity handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        final ErrorResponse response = ErrorResponse.of(HttpStatus.METHOD_NOT_ALLOWED);

        return new ResponseEntity<>(response, HttpStatus.valueOf(response.getStatus()));
    }

    // TODO GlobalExceptionAdvice 기능 추가 3
    @ExceptionHandler
    public ResponseEntity handleException(RuntimeException e) {
        final ErrorResponse response = ErrorResponse.of(HttpStatus.INTERNAL_SERVER_ERROR);

        return new ResponseEntity<>(response, HttpStatus.valueOf(response.getStatus()));
    }

예외응답 추가

//  //
    private int status;
    private String message;

    private ErrorResponse(int status, String message) {
        this.status = status;
        this.message = message;
    }

    public static ErrorResponse of(ExceptionCode exceptionCode) {
        return new ErrorResponse(exceptionCode.getStatus(), exceptionCode.getMessage());
    }

    public static ErrorResponse of(HttpStatus httpStatus) {
        return new ErrorResponse(httpStatus.value(), httpStatus.getReasonPhrase());
    }

//   //

역시 따라쳐보다가 내가 하려니깐 잘 안된다... 그런데 문제가 3개가 있었는데, 1번이 좀 오래걸렸던 거 같고, 레퍼도 찾아보면서 했었다.. 근데 컨트롤러 URI를 잘 못 줘서, 레퍼대로 했음에도 불구하고, 안 나왔었는데 그거 발견하는데 좀 많이 걸렸고, 나머지는 할만했다.... 1번이 풀리고 나니깐, 2번이 생각만큼 어렵지 않은 곳에서 풀렸지만, 어렵게 생각해서 오래걸렸다.. 반면에 3번은 수월했다....

구현 연습!!! 더 해야 한다!!

profile
쌩수 Git >> https://github.com/SsangSoo?tab=repositories

0개의 댓글