exception : handle exception(filter)
This commit is contained in:
24
exception/src/main/java/hello/exception/WebConfig.java
Normal file
24
exception/src/main/java/hello/exception/WebConfig.java
Normal file
@@ -0,0 +1,24 @@
|
||||
package hello.exception;
|
||||
|
||||
import hello.exception.filter.LogFilter;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import javax.servlet.DispatcherType;
|
||||
import javax.servlet.Filter;
|
||||
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Bean
|
||||
public FilterRegistrationBean<Filter> logFilter() {
|
||||
FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<>();
|
||||
filterRegistrationBean.setFilter(new LogFilter());
|
||||
filterRegistrationBean.setOrder(1);
|
||||
filterRegistrationBean.addUrlPatterns("/*");
|
||||
filterRegistrationBean.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ERROR);
|
||||
return filterRegistrationBean;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package hello.exception.filter;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import javax.servlet.*;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
@Slf4j
|
||||
public class LogFilter implements Filter {
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
log.info("log filter init");
|
||||
}
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
|
||||
HttpServletRequest httpRequest = (HttpServletRequest) request;
|
||||
String requestURI = httpRequest.getRequestURI();
|
||||
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
try {
|
||||
log.info("REQUEST [{}][{}][{}]", uuid, request.getDispatcherType(), requestURI);
|
||||
chain.doFilter(request, response);
|
||||
} catch (Exception e) {
|
||||
log.info("EXCEPTION ! {}", e.getMessage());
|
||||
throw e;
|
||||
} finally {
|
||||
log.info("RESPONSE [{}][{}][{}]", uuid, request.getDispatcherType(), requestURI);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void destroy() {
|
||||
log.info("log filter destroy");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user