1. Repository
public class Repository {
public int findById() {
throw new RuntimeException("디비에서 오류가 났어");
}
}
- 조회 시 DB 오류를 가정해 예외를 던진다.
2. Service
public class Service {
private final Repository repository;
public Service(Repository repository) {
this.repository = repository;
}
public int 상세보기() {
return repository.findById();
}
}
Repository
에서 발생한 예외는Service
에서 처리하지 않고 그대로 전달된다.
3. Controller
public class Controller {
private final Service service;
public Controller(Service service) {
this.service = service;
}
public void detail() {
int model = service.상세보기();
System.out.println("렌더링: " + model);
}
}
Repository
에서 발생한 예외는Controller
에서 처리하지 않고 그대로 전달된다.
4. ControllerAdvice
public class ControllerAdvice {
public void process(RuntimeException e) {
System.out.println("에러 공통 처리: " + e.getMessage());
}
}
- 예외가 발생했을 때 공통적으로 처리할 로직을 정의하는
ControllerAdvice
클래스
RuntimeException
예외가 발생할 경우, 이를 받아e.getMessage()
로 예외 메시지를 출력한다.
5. DispatcherServlet
public class DispatcherServlet {
private final Controller controller;
private final ControllerAdvice controllerAdvice;
public DispatcherServlet(Controller controller, ControllerAdvice controllerAdvice) {
this.controller = controller;
this.controllerAdvice = controllerAdvice;
}
public void route(String path) {
try {
if (path.equals("/")) {
controller.list();
} else if (path.equals("/board")) {
controller.detail();
} else {
System.out.println("404 Not Found");
}
} catch (RuntimeException e) {
controllerAdvice.process(e);
}
}
}
DispatcherServlet
을 연습용으로 구현한 클래스
Controller
와ControllerAdvice
를 가지고 있으며,Controller
의 로직 실행 중 예외가 발생하면ControllerAdvice
를 통해 예외를 처리한다.
6. App
public class App {
public static void main(String[] args) {
Repository repository = new Repository();
Service service = new Service(repository);
Controller controller = new Controller(service);
ControllerAdvice controllerAdvice = new ControllerAdvice();
DispatcherServlet dispatcherServlet = new DispatcherServlet(controller, controllerAdvice);
dispatcherServlet.route("/board");
}
}
- 모든 객체를 초기화한 후,
dispatcherServlet.route("/board");
를 호출하여 직접 구현한 예외 처리를 확인한다.
Share article