Backend/Spring
[Spring boot] 예외처리 - GlobalExceptionHandler - ControllerAdvice
romeoh
2019. 10. 15. 16:27
반응형
Spring Boot / Oracle / Mybatis 차례
AuthenticationInterceptor.java
package com.gaeyou.firstproject.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.gaeyou.firstproject.exception.UnauthorizedException;
import com.gaeyou.firstproject.model.PersonModel;
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
Logger log = LoggerFactory.getLogger(AuthenticationInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// log.info("preHandle");
HttpSession httpSession = request.getSession();
PersonModel person = (PersonModel) httpSession.getAttribute("user");
if (person == null) {
log.info("로그아웃 상태");
throw new UnauthorizedException("로그인 해주세요.");
}
log.info("로그인 되어 있음");
httpSession.setMaxInactiveInterval(30*60);
return true;
}
@Override
public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// log.info("postHandle");
super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// log.info("afterCompletion");
super.afterCompletion(request, response, handler, ex);
}
}
GlobalExceptionHandler.java
package com.gaeyou.firstproject.controller;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.gaeyou.firstproject.exception.UnauthorizedException;
@ControllerAdvice
@RestController
public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(value = UnauthorizedException.class)
public String handleBaseException(UnauthorizedException e) {
return e.getMessage();
}
}
UnauthorizedException.java
package com.gaeyou.firstproject.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
public class UnauthorizedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public UnauthorizedException(String message) {
super(message);
}
}
반응형