springboot 全局异常捕获

【springboot 全局异常捕获】案头见蠹鱼,犹胜凡俦侣。这篇文章主要讲述springboot 全局异常捕获相关的知识,希望能为你提供帮助。
package com.example.demo.Config;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**

  • Create with Intellij idea
  • User:Mingtian
  • Date:2018/8/20
  • Time:15:49
  • 全局异常信息
    */
    ??@ControllerAdvice??  //??@ControllerAdvice??  作用:增强型控制器,对于控制器的全局配置放在同一个位置
    public class ErrorException
    /**
  • 应用到所有??@RequestMapping??注解方法,在其执行之前初始化数据绑定器
  • ??@param???  binder
    */
    ??@InitBinder??public void initBinder(WebDataBinder binder)
    /**
  • 把值绑定到Model中,使全局??@RequestMapping??可以获取到该值
  • ??@param???  model
    */
    ???@ModelAttribute???public void addAttributes(Model model,HttpServletRequest request)
    model.addAttribute(“user”, request.getRemoteUser()); //登陆用户

  1. ??//@ExceptionHandler(异常类)这个注解则表示Controller中任何一个方法发生异常,则会被注解了@ExceptionHandler的方法拦截到。??
  2. ??// 对应的异常类执行对应的方法,如果都没有匹配到异常类,则采用近亲匹配的方式。??
  3. ??@ExceptionHandler(value = https://www.songbingjia.com/android/Exception.class)??
  4. ??public Object errorHandler(HttpServletRequest request,??
  5. ??HttpServletResponse response,??
  6. ??Exception e)??
  7. ??e.printStackTrace(); //打印错误信息??
  8. ??ModelAndView mv=new ModelAndView(); ??
  9. ??mv.addObject("url",request.getRequestURL()); //存放请求地址??
  10. ??mv.addObject("exception",e); //存放错误信息??
  11. ??mv.setViewName("error"); //定义的错误页面??
  12. ??return mv; ??
  13. ????

  14. ??//判断是否是ajax请求??
  15. ??public static boolean isAjax(HttpServletRequest request)??
  16. ??return (request.getHeader("X-Requested-With")!=null??
  17. ??& & "XMLRequest".equals(request.getHeader("X-Requested-With").toString())); ??
  18. ????


    推荐阅读