码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot全局异常的捕获设置

时间:2018-04-12 00:17:41      阅读:301      评论:0      收藏:0      [点我收藏+]

标签:object   throw   err   framework   ring   class   全局   turn   style   

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)

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

SpringBoot全局异常的捕获设置

标签:object   throw   err   framework   ring   class   全局   turn   style   

原文地址:https://www.cnblogs.com/yinfengjiujian/p/8799245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!