스프링 익셉션객체는 보안때문에 못넘긴다. 유저정의 익셉션은 객체넘길수있는데 그냥 익셉션객체는 안되.ㅁ 그래서 익셉션.겟메세지 , 익셉션.스택트래이스 이렇게 따로따로 넘겨줘야함.
Exception 객체는 내부에 민감한 정보(예: 서버 경로, 클래스 정보, 라이브러리 경로 등)를 포함하고 있을 수 있어요.NullPointerException을 전체 출력하면 코드 내부 구조를 유추할 수 있게 되죠.try {
// some code
} catch (Exception e) {
model.addAttribute("errorMessage", e.getMessage());
model.addAttribute("stackTrace", e.getStackTrace());
return "errorPage";
}
e.getMessage() → 에러 요약 메시지e.getStackTrace() → 구체적인 위치, 필요하면 로깅 전용으로 사용public class MyCustomException extends RuntimeException {
private int errorCode;
public MyCustomException(String message, int errorCode) {
super(message);
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
}
에러 코드, 간단한 메시지만 전달합니다.@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MyCustomException.class)
public ResponseEntity<ErrorResponse> handleCustomException(MyCustomException e) {
return new ResponseEntity<>(new ErrorResponse(e.getMessage(), e.getErrorCode()), HttpStatus.BAD_REQUEST);
}
}