zoukankan      html  css  js  c++  java
  • SpringBoot全局异常的捕获设置

    1、新建立一个捕获异常的实体类

    如:LeeExceptionHandler

     1 package com.leecx.exception;
     2 
     3 import javax.servlet.http.HttpServletRequest;
     4 import javax.servlet.http.HttpServletResponse;
     5 
     6 import org.springframework.web.bind.annotation.ControllerAdvice;
     7 import org.springframework.web.bind.annotation.ExceptionHandler;
     8 import org.springframework.web.servlet.ModelAndView;
     9 
    10 @ControllerAdvice
    11 public class LeeExceptionHandler {
    12     
    13     public static final String DEFAULT_ERROR_VIEW = "error";
    14     
    15 
    16     
    17     @ExceptionHandler(value = Exception.class)
    18     public Object errorHandler(HttpServletRequest reqest, HttpServletResponse response, Exception e) throws Exception {
    19         
    20         e.printStackTrace();
    21         
    22         if (isAjax(reqest)) {
    23             return response;
    24         } else {
    25             ModelAndView mav = new ModelAndView();
    26             mav.addObject("exception", e);
    27             mav.addObject("url", reqest.getRequestURL());
    28             mav.setViewName(DEFAULT_ERROR_VIEW);
    29             return mav;
    30         }
    31     }
    32     
    33     
    34     public static boolean isAjax(HttpServletRequest httpRequest){
    35         return  (httpRequest.getHeader("X-Requested-With") != null  && "XMLHttpRequest".equals( httpRequest.getHeader("X-Requested-With").toString()) ) ;
    36     }
    37 
    38     
    39 }

    在类上面加入注解:@ControllerAdvice

    在处理方法上面加入注解@ExceptionHandler(value = Exception.class)

    然后设置相应的业务处理。跳转到 特需的处理错误的友好业务界面。

  • 相关阅读:
    关系数据模型和对象数据模型之间的对应关系
    object中的方法
    重写与重载
    java中的多态总结
    int是java.lang包中可用的类的名称
    abstract关键字的说法
    7迭代器
    6python *args **kwargs
    1特征工程
    1html
  • 原文地址:https://www.cnblogs.com/yinfengjiujian/p/8799245.html
Copyright © 2011-2022 走看看