Service Code
@Override
public void CheckFlag(Integer flag) {
if (flag == 1)
throw new TempHandler(Code.TEMP_EXCEPTION);
}
TempHandler
package com.umc.ttg.domain.store.application.handler;
import com.umc.ttg.global.common.ResponseCode;
import com.umc.ttg.global.error.GeneralException;
public class TempHandler extends GeneralException {
public TempHandler(ResponseCode errorCode) {
super(errorCode);
}
}
Service 가 해당 Handler 를 생성하면(생성자로) GeneralException 을 만듦
→ super 가 부모 클래스의 생성자를 호출하는 것이므로
Handler 를 생성하면 GeneralException 클래스에서 오버로딩 해둔 생성자가 호출됨(아래의 코드)
public GeneralException(ResponseCode errorCode) {
super(errorCode.getMessage());
this.errorCode = errorCode;
}
GeneralException 은 RuntimeException 상속 받음

그 이유는 MasterExceptionHandler 가 @RestControllerAdivce 를 가지고 있기 때문

MasterExceptionHandler 의 코드에서 GenralException 에 대해 오버로딩된 함수를 호출하고 있음
@org.springframework.web.bind.annotation.ExceptionHandler
public ResponseEntity<Object> general(GeneralException e, WebRequest request) {
return handleExceptionInternal(e, e.getErrorCode(), request);
}
위의 코드를 보면 호출된 함수에서 다시 한번 오버로딩된 함수를 호출
private ResponseEntity<Object> handleExceptionInternal(Exception e, ResponseCode errorCode,
WebRequest request) {
return handleExceptionInternal(e, errorCode, HttpHeaders.EMPTY, errorCode.getHttpStatus(),
request);
}
최종적으로 다시 한번 호출된 함수에서는 상속 받은 부모 클래스의 생성자 호출
private ResponseEntity<Object> handleExceptionInternal(Exception e, ResponseCode errorCode,
HttpHeaders headers, HttpStatus status, WebRequest request) {
BaseResponseDto<Object> body = BaseResponseDto.onFailure(errorCode);
return super.handleExceptionInternal(
e,
body,
headers,
status,
request
);
}
부모 코드를 까보면, 응답을 보내는 것을 알 수 있음
@Nullable
protected ResponseEntity<Object> handleExceptionInternal(
Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatusCode statusCode, WebRequest request) {
if (request instanceof ServletWebRequest servletWebRequest) {
HttpServletResponse response = servletWebRequest.getResponse();
if (response != null && response.isCommitted()) {
if (logger.isWarnEnabled()) {
logger.warn("Response already committed. Ignoring: " + ex);
}
return null;
}
}
if (statusCode.equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex, WebRequest.SCOPE_REQUEST);
}
if (body == null && ex instanceof ErrorResponse errorResponse) {
body = errorResponse.updateAndGetBody(this.messageSource, LocaleContextHolder.getLocale());
}
return createResponseEntity(body, headers, statusCode, request);
}
@RestController 가 붙은 대상에서 Exception 이 발생하는 것을 감지하는 역할
@RestController 가 붙은 Controller 에서 호출했으므로, 컨트롤러에서 Exception 발생한 것으로 판단