zoukankan      html  css  js  c++  java
  • Spring 全局异常处理

    主要介绍  @ControllerAdvice 注解方式

    代码:

    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        @ExceptionHandler(Exception.class)
        public ModelAndView globalHandler(HttpServletRequest request,
                HttpServletResponse response, Exception ex) {
            ModelAndView mv = new ModelAndView(new MappingJackson2JsonView());
            if (!isAnsynJsonRequest(request)) {
                mv = new ModelAndView("error/500");
            }
            mv.addObject("code", 500);
            mv.addObject("msg", "系统异常");
            mv.addObject("message", ex.getMessage());
            mv.addObject("detail", ex.getClass().getName());
            mv.addObject("cause root", ex.getStackTrace()[0]);
            return mv;
    
        }
    
        private boolean isAnsynJsonRequest(HttpServletRequest request) {
            return request.getRequestURI().contains("/api")
                    || request.getHeader("accept").contains("application/json")
                    || (request.getHeader("X-Requested-With") != null && request
                            .getHeader("X-Requested-With").contains(
                                    "XMLHttpRequest"));
        }
    }

     其中 isAnsynJsonRequest 方法用于判断当前请求是否是异步或者是 /api路径(一般api只返回数据不返回页面)

    error/500是 WEB-INF/目录下的错误页面的路径

  • 相关阅读:
    db_keep_cache_size參数的控制范围測试
    怎样写面向互联网公司的求职简历
    servlet获取参数
    mybatis
    java常用API
    java IO
    ajax创建
    java 泛型中 T、E ... 和 问号(通配符)的区别
    java Arrays对数组操作
    org.json 使用
  • 原文地址:https://www.cnblogs.com/silfox/p/9779468.html
Copyright © 2011-2022 走看看