서비스 특성에 맞춘 예외처리 방법 Custom Exception

이경영·2022년 10월 19일
0

스프링부트2

목록 보기
17/19

출처 : https://youtu.be/5XHhAhN-9po

HttpStatus

Httpstatus는 Enum 클래스임

Enum Class

  • 서로 관련 있는 상수들을 모아 심볼릭한 명칭의 집합으로 정의한 것
  • 클래스처럼 보이게 하는 상수

주요 항목

Custom Exception

error type, error code, message에서 필요한 내용은 아래와 같음
error type : HttpStatus의 reasonPhrase
error code : HttpStatus의 value
message : 상황별 디테일 Message


실습

Constant.java

package com.example.testproject.common.exception;

public class Constants {
    public enum ExceptionClass{
        PRODUCT("Product"), ORDER("Order"), PROVIDER("Provider");

        private String exceptionClass;

        ExceptionClass(String exceptionClass){ this.exceptionClass = exceptionClass;}

        public String getExceptionClass(){ return exceptionClass; }

        @Override
        public String toString(){
            return getExceptionClass() + " Exception. ";

        }
    }
}
  • AroundHubException.java
package com.example.testproject.common.exception;

import org.springframework.http.HttpStatus;

import java.io.Serial;

public class AroundHubException extends Exception{ //Exception 상속
    @Serial
    private static final long serialVersionUID = 1734030261431668714L;

    private Constants.ExceptionClass exceptionClass;
    private HttpStatus httpStatus;

    //생성자를 받는 값.
    public AroundHubException(Constants.ExceptionClass exceptionClass, HttpStatus httpStatus, String message){
        super(exceptionClass.toString() + message); //메세지 값 정의 : Product Exception 값이 toString으로 출력됨.
        this.exceptionClass=exceptionClass;
        this.httpStatus=httpStatus;
    }

    public Constants.ExceptionClass getExceptionClass(){
        return exceptionClass;
    }

    public int getHttpStatusCode(){
        return httpStatus.value();
    }

    public String getHttpStatusType(){
        return httpStatus.getReasonPhrase();
    }

    public HttpStatus getHttpStatus(){
        return httpStatus;
    }


}
  • AroundHubExceptionHandler.java
package com.example.testproject.common.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

//@RestControllerAdvice : Controller 단의 예외처리는 모두 여기서 처리한다.
@RestControllerAdvice
public class AroundHubExceptionHandler {
    private final Logger LOGGER= LoggerFactory.getLogger(AroundHubExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Map<String,String>> ExceptionHandler(Exception e){
        HttpHeaders responseHeaders=new HttpHeaders();
        HttpStatus httpStatus=HttpStatus.BAD_REQUEST;

        LOGGER.info("Advice 내 ExceptionHandler 호출");

        Map<String,String> map=new HashMap<>();
        map.put("error type", httpStatus.getReasonPhrase());
        map.put("code", "400");
        map.put("message", "에러 발생");

        return new ResponseEntity<>(map, responseHeaders, httpStatus);
    }

    @ExceptionHandler(value= AroundHubException.class)
    public ResponseEntity<Map<String,String>> ExceptionHandler(AroundHubException e){
        HttpHeaders responseHeaders=new HttpHeaders();

        Map<String,String> map=new HashMap<>();
        map.put("error type", e.getHttpStatusType());
        map.put("error code", Integer.toString(e.getHttpStatusCode())); //Map<String, Object>로 설정하면 변환작업 불필요
        map.put("message", e.getMessage());

        return new ResponseEntity<>(map, responseHeaders, e.getHttpStatus());
    }
}
  • ProductController.java
    @PostMapping(value = "/product/exception")
    public void exceptionTest() throws AroundHubException{
        throw new AroundHubException(Constants.ExceptionClass.PRODUCT, HttpStatus.BAD_REQUEST, "의도한 에러가 발생했습니다." );
        //HttpStatus.FORBIDDEN, "접근이 금지되었습니다" 로 바꿀 수 있음.
    }

profile
꾸준히

0개의 댓글