• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >Java > SpringBoot初始教程之统一异常处理详解

SpringBoot初始教程之统一异常处理详解

作者:尊少 字体:[增加 减小] 来源:互联网 时间:2017-05-28

尊少 通过本文主要向大家介绍了springboot详解,springboot注解详解,springboot 异常处理,springboot是什么,springboot教程等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

1.介绍

在日常开发中发生了异常,往往是需要通过一个统一的异常处理处理所有异常,来保证客户端能够收到友好的提示。SpringBoot在页面发生异常的时候会自动把请求转到/error,SpringBoot内置了一个BasicErrorController对异常进行统一的处理,当然也可以自定义这个路径

application.yaml

server:
 port: 8080
 error:
 path: /custom/error
</div>

BasicErrorController提供两种返回错误一种是页面返回、当你是页面请求的时候就会返回页面,另外一种是json请求的时候就会返回json错误

 @RequestMapping(produces = "text/html")
 public ModelAndView errorHtml(HttpServletRequest request,
   HttpServletResponse response) {
  HttpStatus status = getStatus(request);
  Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
    request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
  response.setStatus(status.value());
  ModelAndView modelAndView = resolveErrorView(request, response, status, model);
  return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
 }

 @RequestMapping
 @ResponseBody
 public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
  Map<String, Object> body = getErrorAttributes(request,
    isIncludeStackTrace(request, MediaType.ALL));
  HttpStatus status = getStatus(request);
  return new ResponseEntity<Map<String, Object>>(body, status);
 }

</div>

分别会有如下两种返回

{
 "timestamp": 1478571808052,
 "status": 404,
 "error": "Not Found",
 "message": "No message available",
 "path": "/rpc"
}
</div>

2.通用Exception处理

通过使用@ControllerAdvice来进行统一异常处理,@ExceptionHandler(value = Exception.class)来指定捕获的异常

下面针对两种异常进行了特殊处理分别返回页面和json数据,使用这种方式有个局限,无法根据不同的头部返回不同的数据格式,而且无法针对404、403等多种状态进行处理

 @ControllerAdvice
 public class GlobalExceptionHandler {
  public static final String DEFAULT_ERROR_VIEW = "error";
  @ExceptionHandler(value = CustomException.class)
  @ResponseBody
  public ResponseEntity defaultErrorHandler(HttpServletRequest req, CustomException e) throws Exception {
   return ResponseEntity.ok("ok");
  }
  @ExceptionHandler(value = Exception.class)
  public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
   ModelAndView mav = new ModelAndView();
   mav.addObject("exception", e);
   mav.addObject("url", req.getRequestURL());
   mav.setViewName(DEFAULT_ERROR_VIEW);
   return mav;
  }
 }

</div>

3.自定义BasicErrorController 错误处理

在初始介绍哪里提到了BasicErrorController,这个是SpringBoot的默认错误处理,也是一种全局处理方式。咱们可以模仿这种处理方式自定义自己的全局错误处理

下面定义了一个自己的BasicErrorController,可以根据自己的需求自定义errorHtml()和error()的返回值。

 @Controller
 @RequestMapping("${server.error.path:${error.path:/error}}")
 public class BasicErrorController extends AbstractErrorController {
  private final ErrorProperties errorProperties;
  private static final Logger LOGGER = LoggerFactory.getLogger(BasicErrorController.class);
  @Autowired
  private ApplicationContext applicationContext;

  /**
   * Create a new {@link org.springframework.boot.autoconfigure.web.BasicErrorController} instance.
   *
   * @param errorAttributes the error attributes
   * @param errorProperties configuration properties
   */
  public BasicErrorController(ErrorAttributes errorAttributes,
         ErrorProperties errorProperties) {
   this(errorAttributes, errorProperties,
     Collections.<ErrorViewResolver>emptyList());
  }

  /**
   * Create a new {@link org.springframework.boot.autoconfigure.web.BasicErrorController} instance.
   *
   * @param errorAttributes the error attributes
   * @param errorProperties configuration properties
   * @param errorViewResolvers error view resolvers
   */
  public BasicErrorController(ErrorAttributes errorAttributes,
         ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
   super(errorAttributes, errorViewResolvers);
   Assert.notNull(errorProperties, "ErrorProperties must not be null");
   this.errorProperties = errorProperties;
  }

  @Override
  public String getErrorPath() {
   return this.errorProperties.getPath();
  }

  @RequestMapping(produces = "text/html")
  public ModelAndView errorHtml(HttpServletRequest request,
          HttpServletResponse response) {
   HttpStatus status = getStatus(request);
   Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
     request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
   response.setStatus(status.value());
   ModelAndView modelAndView = resolveErrorView(request, response, status, model);
   insertError(request);
   return modelAndView == null ? new ModelAndView("error", model) : modelAndView;
  }



  @RequestMapping
  @ResponseBody
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
   Map<String, Object> body = getErrorAttributes(request,
     isIncludeStackTrace(request, MediaType.ALL));
   HttpStatus status = getStatus(request);
   insertError(request);
   return new ResponseEntity(body, status);
  }

  /**
   * Determine if the stacktrace attribute should be included.
   *
   * @param request the source request
   * @param produces the media type produced (or {@code MediaType.ALL})
   * @return if the stacktrace attribute should be included
   */
  protected boolean isIncludeStackTrace(HttpServletRequest request,
            MediaType produces) {
   ErrorProperties.IncludeStacktrace include = getErrorProperties().getIncludeStacktrace();
   if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
    return true;
   }
   if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {
    return getTraceParameter(request);
   }
   return false;
  }

  /**
   * Provide access to the error properties.
   *
   * @return the error properties
   */
  protected ErrorProperties getErrorProperties() {
   return this.errorProperties;
  }
 }

</div>

SpringBoot提供了一种特殊的Bean定义方式,可以让我们容易的覆盖已经定义好的Controller,原生的BasicErrorController是定义在ErrorMvcAutoConfiguration中的

具体代码如下:

 @Bean
 @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
 public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
  return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
    this.errorViewResolvers);
 }
</div>

可以看到这个注解@ConditionalOnMissingBean 意思就是定义这个bean 当 ErrorController.class 这个没有定义的时候, 意思就是说只要我们在代码里面定义了自己的ErrorController.class时,这段代码就不生效了,具体自定义如下:

 @Configuration
 @ConditionalOnWebApplication
 @ConditionalOnClass({Servlet.class, DispatcherServlet.class})
 @AutoConfigureBefore(WebMvcAutoConfiguration.class)
 @EnableConfigurationProperties(ResourceProperties.class)
 public class ConfigSpringboot {
  @Autowired(required = false)
  private List<ErrorViewResolver> errorViewResolvers;
  private final 



 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • springboot整合freemarker详解
  • 详解SpringBoot AOP 拦截器(Aspect注解方式)
  • 详解SpringBoot配置devtools实现热部署
  • springboot全局异常处理详解
  • 详解springboot + profile(不同环境读取不同配置)
  • springboot中thymeleaf模板使用详解
  • 详解springboot+mybatis多数据源最简解决方案
  • 详解springboot整合mongodb
  • 详解在SpringBoot应用中获取应用上下文方法
  • 详解springboot配置多个redis连接

相关文章

  • 2017-05-28java 中ThreadLocal 的正确用法
  • 2017-05-28String类下compareTo()与compare()方法比较
  • 2017-05-28SpringMVC接收页面表单参数
  • 2017-05-28java获取redis日志信息与动态监控信息的方法
  • 2017-05-28Spring boot将配置属性注入到bean类中
  • 2017-05-28spring启动加载程序的几种方法介绍
  • 2017-05-28java实现ftp文件上传下载功能
  • 2017-05-28SpringMVC中使用bean来接收form表单提交的参数时的注意点
  • 2017-05-28Java缓存池代码实例详解
  • 2017-05-28ByteArrayOutputStream简介和使用_动力节点Java学院整理

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • java中添加按钮并添加响应事件的方法(推荐)
    • 简述Java中进程与线程的关系_动力节点Java学院整理
    • Java 选择排序、插入排序、希尔算法实例详解
    • Java递归算法详解(动力节点整理)
    • 解决Tomcat修改get提交请求乱码问题
    • Spring Boot集成MyBatis访问数据库的方法
    • JAVA简单工厂模式(从现实生活角度理解代码原理)
    • Jaxb2实现JavaBean与xml互转的方法详解
    • Java程序员新手老手常用的八大开发工具
    • java poi解析word的方法

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有