오류와 예외
error(오류) - 개발자가 미리 예측할 수 없고 발생한다면 프로그램을 종료해야 할 수준의 문제
exception(예외) - 개발자가 구현한 로직에서 발생한 실수나 사용자의 영향에 의해 발생한다. 오류와 달리 개발자가 미리 예측하여 방지할 수 있기에 상황에 맞는 예외처리(Exception Handle)를 해야한다.
오류와 예외 모두 자바의 최상위 클래스인 Object를 상속받는다.
그리고 그 사이에는 Throwable 클래스와 상속관계가 있는데, Throwable 클래스의 역할은 오류나 예외에 대한 메시지를 담는 것이다. 대표적으로 getMessage() 와 printStackTrace() 메서드가 바로 이 클래스에 속해 있다.
당연히 Throwable을 상속받은 Error와 Exception 클래스에서도 위 두 메서드를 사용할수 있게 된다.
try - catch
@GetMapping("/getallmember")
public ResponseEntity getAllMember(Pageable pageable) {
Page<Member> memberPage;
// 반복적으로 발생하는 Try-Catch
try {
memberPage = memberFindService.getAllMemberPage(pageable);
} catch (RuntimeException re) {
return ResponseEntity.badRequest().build();
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
return ResponseEntity.ok().body(MemberAdminDto.Info.of(memberPage));
}
컨트롤러를 작성하다보면 위와 같이 try-catch 구문을 반복적으로 작성해야할 때가 있다. 이는 개발자로서 효율도 떨어지고 코드의 가독성도 떨어지게 된다.
이러한 반복작업을 피하기위해 spring의 @ExceptionHandler
사용하면된다.
@ExceptionHandler
@ExceptionHandler는 @Controller, @RestController가 적용된 Bean내에서 발생하는 예외를 잡아서 하나의 메서드에서 처리해주는 기능을 한다.
@Controller
public class MyController {
...
...
@ExceptionHandler(NullPointerException.class)
public Object nullex(Exception e) {
System.err.println(e.getClass());
return "myService";
}
}
위와 같이 컨트롤러에 nullex라는 메서드를 작성하고, nullpointException이 발생하면 nullex가 자동으로 호출된다.
@ControllerAdvise
@Controller는 전역에서 발생할 수 있는 예외를 잡아 처리해주는 annotation이다.
대표적인 기능으로
com
|-- example
| |-- myapp
| |-- controller
| |-- service
| |-- exception
@ControllerAdvice 클래스를 생성하려면 exception 패키지 아래에 클래스를 생성하면 된다.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGlobalException(Exception ex) {
// 예외 처리 로직
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");
}
@ModelAttribute
public void addCommonAttributes(Model model) {
// 모든 뷰에 공통으로 전달할 속성 추가
model.addAttribute("commonAttribute", "Common Data");
}
// 기타 다른 메서드 정의 가능
}
예외처리 클래스에 @ControllerAdvice 어노테이션을 달아준후 예외처리할 메서드에 @ExceptionHandler 메서드를 달아준다.
유익한 자료 감사합니다.