Eclipse搭建springboot项目(六)全局异常

本文详细介绍SpringBoot2.x中如何配置全局异常处理,包括使用@ControllerAdvice和@RestControllerAdvice注解来捕获并处理不可知异常,同时介绍了如何通过Thymeleaf返回自定义异常界面,实现更友好的错误页面展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

知识点:

  1、SpringBoot2.x服务端异常和SpringBoot配置全局异常

    1)、默认异常测试 int i = 1/0,不友好
    2)、异常注解介绍
    @ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody

    //捕获全局异常,处理所有不可知的异常
    @ExceptionHandler(value=Exception.class)

  2、SpringBoot2.x配置全局异常返回自定义异常和错误页面跳转

    1)、返回自定义异常界面,需要引入thymeleaf依赖
  

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

    2)、resource目录下新建templates,并新建error.html

ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
modelAndView.addObject("msg", e.getMessage());
return modelAndView;

     https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-error-handling

posted on 2019-06-01 22:47 MatrixRhythm 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/aaronRhythm/p/10961336.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值