오늘은 예외처리를 전역처리하는 방법과 컨트롤러 단에서 처리하는방법
그리고 AOP를 활용하는 방법에 대해서 공부해봤습니다.
@RestController
public class TestController {
private final User user = userRepository.getUser(UserController.class);
// 예외 핸들러
@ExceptionHandler(IllegalArgumentException.class)
public String ExceptionHandler(Exception e) {
user.error(e.getMessage());
return "400";
}
// 두개의 예외 핸들러
@ExceptionHandler({IllegalArgumentException.class, TokenMgrError.class})})
public String ExceptionHandler(Exception e) {
user.error(e.getMessage());
return "400";
}
@GetMapping("Test1")
public String Test1() {
throw new IllegalArgumentException("Test Error "); // 강제로 예외 발생
}
두개를 받고싶을때는 중괄호를 해주면된다.
아니면 두개의 메소드를 만들어서 해결하면 된다.
(@ControllerAdvice, @RestControllerAdvice(@ControllerAdvice + @ResponseBody))
문자열로 보내는법과 Dto형태로 보내고 싶을때
@RestControllerAdvice
public class ApiExceptionHandler
//Dto형태로 보내고 싶다면 이런형태로
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Object> apiHandlerRequestException(IllegalArgumentException ex) {
log.warn(ex.getMessage());
return new ResponseEntity(
restApiException,
HttpStatus.BAD_REQUEST
);
}
//문자열로 보내고 싶다면 이러한 형태로 하면된다.
@ExceptionHandler(TestException.class)
public String testHandlerException(Exception e) {
log.warn(ex.getMessage());
return "/400";
}
참조사이트1
로깅에 대한 추상 레이어를 제공하는 인터페이스의 모음이다. (로깅 Facade)
인터페이스를 사용하여 로깅을 구현하게 되면 좋은 점은 추후에 필요로 의해 로깅 라이브러리를 변경할 때 코드의 변경 없이 가능하다는 점이다.
@Slf4j
public class TestController {
@GetMapping("/")
public String String(String str){
try {
str.toString();
} catch (NullPointerException e){
log.trace("가장 디테일한 로그");
log.warn("경고");
log.info("정보성 로그");
log.debug("디버깅용 로그");
log.error("에러",e);
}
return "test";
}
}
로깅 레벨은 (많은 로깅) trace > warn > info > debug > error (적은 로깅) 순이다.