프로젝트

[SpringBoot 예외처리] 커스텀 Exception 처리

nineDeveloper 2020. 6. 20.
728x90

Exception 처리

커스텀 Exception 클래스 생성

에러 처리를 하고자 하는 항목에 대한 커스텀 Exception 클래스를 생성한다

생성 위치는 exception 패키지의 해당 업무 패키지 내에 생성 하면된다

생성 후 SerialVersionUID를 생성한다
SerialVersionUID 생성은 SerialVersionUID 생성 가이드 참조

예시의 파일은 imisFile 로직이므로 exception.imisFile 패키지에 생성되어 있다

예시) ImisFileAwsS3ProcessException 클래스 파일

/**
 * Created by KMS on 25/09/2019.
 * 필수 파라메터 확인
 */
public class ImisFileRequestParamRequiredException extends RuntimeException {

    private static final long serialVersionUID = 5466524715629238130L;

    public ImisFileRequestParamRequiredException() {
        super();
    }

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

    public ImisFileRequestParamRequiredException(String message, Throwable cause) {
        super(message, cause);
    }

    public ImisFileRequestParamRequiredException(Throwable cause) {
        super(cause);
    }

    public ImisFileRequestParamRequiredException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

커스텀 Exception 을 사용한 에러 처리

아래와 같이 throw new ImisFileRequestParamRequiredException 으로 커스텀 Exception을 발생시키면
ImisFileRequestParamRequiredException으로 설정 되어있는 @ExceptionHandler 에서 처리할 수 있다

/**
 * 파일등록 파라메터 값 Empty 체크
 * @return
 */
public String isEmptyToString() {
    StringJoiner result = new StringJoiner(", ");
    if(!ObjectUtils.allNotNull(this.category, this.type)){
        if(this.category == null)
            result.add("category");
        if(!this.isTemporary() && this.contractId == null)
            result.add("contractId");
        if(this.type == null)
            result.add("type");

        log.debug("["+result.toString()+"] 는(은) 필수값 입니다");
        throw new ImisFileRequestParamRequiredException("파라메터 필수값 누락 :: ["+result.toString()+"] 는(은) 필수값 입니다");
    }
    return null;
}

@ExceptionHandler로 처리 하지 않는 에러

@ExceptionHandler로 설정하지 않고 에러 확인만 하면 되는 경우에는 아래와 같이 작성할 수 있다

/**
 * S3에 파일 최종 업로드 처리
 * @param s3UploadFile 업로드할 파일
 * @param path S3에 저장될 상세 경로(경로 + 파일명)
 * @return
 */
private String putS3(File s3UploadFile, Path path) {
    Map<String, Object> errorMap = new HashMap<>();

    try {
        amazonS3Client.putObject(new PutObjectRequest(bucket, String.valueOf(path), s3UploadFile)
                .withCannedAcl(CannedAccessControlList.PublicRead));
    } catch (AmazonServiceException ase) {
        //errorMap.put("AmazonServiceException","Caught an AmazonServiceException from PUT requests, rejected reasons:");
        errorMap.put("Fail FileName:",s3UploadFile.getName());
        errorMap.put("Fail Path:",path);
        errorMap = getErrorMap(errorMap, ase);
        log.error("[S3] Upload Fail [putS3] :: AmazonServiceException :: {}",errorMap);
        return null;
    } catch (AmazonClientException ace) {
        errorMap.put("Fail FileName:",s3UploadFile.getName());
        errorMap.put("Fail Path:",path);
        errorMap = getErrorMap(errorMap, ace);
        log.error("[S3] Upload Fail [putS3] :: AmazonClientException :: {}",errorMap);
        return null;
    }
    return amazonS3Client.getUrl(bucket, String.valueOf(path)).toString();
}

ErrorMap 생성

ErrorMapinstanceofException에 따라 분기를 태워 생성되도록 하였따

/**
 * AWS Exception 에러 메세지 셋팅
 * @param errorMap
 * @param error
 * @return
 */
private Map<String, Object> getErrorMap(Map<String, Object> errorMap, Object error) {
    if(error instanceof AmazonServiceException) {
        AmazonServiceException ase = (AmazonServiceException) error;
        errorMap.put("Error Message:", ase.getMessage());
        errorMap.put("HTTP Status Code:", ase.getStatusCode());
        errorMap.put("AWS Error Code:", ase.getErrorCode());
        errorMap.put("Error Type:", ase.getErrorType());
        errorMap.put("Request ID:", ase.getRequestId());
    } else if(error instanceof AmazonClientException) {
        AmazonClientException ace = (AmazonClientException) error;
        errorMap.put("Error Message:",ace.getMessage());
    }
    return errorMap;
}
728x90

댓글

💲 추천 글