zoukankan      html  css  js  c++  java
  • 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 = 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. }
  • 相关阅读:
    实验2实验报告
    实验1实验报告
    汇编实验九
    汇编实验5
    汇编实验四
    汇编实验三
    汇编实验二
    汇编实验一
    汇编第一章
    浅谈webpack4.0 性能优化
  • 原文地址:https://www.cnblogs.com/ming-blogs/p/10288823.html
Copyright © 2011-2022 走看看