오늘은 몰랐으면 내일은 알면 된다
2022-12-14 (4) Controller의 Exception 처리 Advice 본문
try catch가 너무 많은 부분을 잡아먹고 있다.
AOP를 활용하여 이를 분리해보자. Advice로 예외처리를 Weaving 할 것이다.
[@ControllerAdvice]
: AOP를 이용하는 방식이다. @ControllerAdvice 어노테이션을 붙여준다. @ExceptionHandler를 통해 예외처리를 진행한다.
이제 적용을 해보자. 먼저 Controller에서 try catch를 모두 삭제하고, throw 처리한다.
- 기존코드
@PostMapping("boardwrite")
@ResponseBody
public ResponseEntity<?> boardWrite(HttpSession session,
@RequestPart(required = false) List<MultipartFile> files,
@RequestPart(required = false) MultipartFile file,
RepBoard rb) {
String loginedId = (String) session.getAttribute("loginedId");
try {
Customer c = new Customer();
c.setId(loginedId);
rb.setBoardC(c);
service.writeBoard(files, file, rb);
return new ResponseEntity<>(HttpStatus.OK);
} catch (AddException e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
- 변경코드
@PostMapping("boardwrite")
@ResponseBody
public ResponseEntity<?> boardWrite(HttpSession session,
@RequestPart(required = false) List<MultipartFile> files,
@RequestPart(required = false) MultipartFile file,
RepBoard rb) throws AddException {
String loginedId = (String) session.getAttribute("loginedId");
Customer c = new Customer();
c.setId(loginedId);
rb.setBoardC(c);
service.writeBoard(files, file, rb);
return new ResponseEntity<>(HttpStatus.OK);
}
이제 Advice를 만든다.
@ControllerAdvice
public class MyControllerAdvice {
@ExceptionHandler(Exception.class)
public ResponseEntity<?> except(Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
AddException이 발생한다면, 위의 Advice가 처리를 하게 될 것이다.

새로운 패키지를 만들었으므로 ServletContext의 component scan 에도 등록해준다.
@Configuration
@ComponentScan(basePackages = {"control", "advice"})
@EnableWebMvc
public class MyServletContext implements WebMvcConfigurer {
그 다음 Exception을 발생시켜보면, Advice를 잘 타는 것을 확인할 수 있다.

'Java > JAVA 개발자 양성과정' 카테고리의 다른 글
| 2022-12-15 (2) 트랜잭션 처리 (0) | 2022.12.15 |
|---|---|
| 2022-12-15 (1) Controller Advice (0) | 2022.12.15 |
| 2022-12-14 (3) 스프링 MVC (0) | 2022.12.14 |
| 2022-12-14 (2) myBatis xml Java 클래스 변환 (0) | 2022.12.14 |
| 2022-12-14 (1) OrderMapper.xml 만들기 (0) | 2022.12.14 |