玩命加载中 . . .

springboot自定义拦截器和全局异常处理器


springboot自定义拦截器和全局异常处理器

一、自定义拦截器

  1. 创建web的全局配置类
    1. @Configuration
    2. 继承WebMvcConfigurerAdapter
@Configuration//声明这是一个配置
public class MyInterceptor extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        HandlerInterceptor inter = new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
                System.out.println("自定义拦截器......");
                return true;
            }
            @Override
            public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
                throws Exception {
                // TODO Auto-generated method stub
            }
            @Override
            public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
                throws Exception {
                // TODO Auto-generated method stub

            }
        };
        registry.addInterceptor(inter).addPathPatterns("/**");
    }
}

二、全局异常处理器

//全局异常处理器
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String, Object> handleException(Exception exception) {
        Map<String, Object> map = new HashMap<>();
        map.put("errorCode", 500);
        map.put("errorMsg", exception.toString());
        return map;
    }
}

文章作者: 小苏
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小苏 !
评论
  目录