Language/Java

Springboot Custom Exception

아르비스 2020. 6. 23. 10:38

RestAPI 를 활용한 서비스 구성시, Custom하게 Exception을 처리하고 싶을때가 종종 발생함.

이를 위한, Custom Exception 생성 및 처리 방법 

 

ex)

throw new SecurityException(HttpStatus.INTERNAL_SERVER_ERROR, filePath + " 파일을 찾을 수 없습니다.");

throw new SecurityException(HttpStatus.UNAUTHORIZED,"Token Key is invalid");

 응답으론 Http Response에 기본 Status와 Json Message만 줄수 있다.

 

Spring MVC 에 의해서..

1) Exception 생성

import org.springframework.http.HttpStatus;

public class SecurityException extends RuntimeException {
    private static final long serialVersionUID = -7806029002430564887L;

    private String message;
    private HttpStatus status;

    public SecurityException() {
    }

    public SecurityException(HttpStatus status, String message) {
        this.status = status;
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public HttpStatus getStatus() {
        return status;
    }

    public void setStatus(HttpStatus status) {
        this.status = status;
    }
}

 

2) Response 생성

import org.springframework.http.HttpStatus;

public class SecurityResponse {
    private String error;
    private HttpStatus status;

    public SecurityResponse() {

    }

    public SecurityResponse(HttpStatus status, String error) {
        this.status = status;
        this.error = error;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public HttpStatus getStatus() {
        return status;
    }

    public void setStatus(HttpStatus status) {
        this.status = status;
    }
}

 

 

3) Exception Response 객체 Mapping

@ControllerAdvice
	public class SecurityControllerAdvice {

		@ExceptionHandler(SecurityException.class)
		@ResponseBody
		public ResponseEntity<Object> handleSecurityException(SecurityException se, WebRequest request) {
			Map<String, Object> response = new HashMap<>();

			response.put("message", se.getMessage());
			return new ResponseEntity<>(response, se.getStatus());
		}
	}

 

4) Code 적용

throw new SecurityException(HttpStatus.UNAUTHORIZED,"Token Key is invalid");

throw new SecurityException(HttpStatus.INTERNAL_SERVER_ERROR,"Date Source [ "+ dsName + " ]  is invalid");

 

 

참 쉽죠잉~~