springboot实现全局异常处理

对于springboot项目来说,业务代码频繁的使用try catch是非常不友好的,而且代码不美观,因此,需要对全局异常进行统一处理。

本文将介绍如何使用@ControllerAdvice和@ExceptionHandler来对异常进行统一处理。

一.目录结构

二.目录下文件内容

        2.1 pom.xml          

        在pom.xml文件中,只需要引入web依赖即可

<parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.6.2</version>
    </parent>

    <dependencies>
        <!--  web依赖      -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

        2.2 application.yml

        这里只是简单的配了下启动端口。

server:
  port: 8080

        2.3 GlobalExceptionHandler.class

        这里将@ControllerAdvice注解标注在需要声明全局异常处理的类上面,将@ExceptionHandler注解放在异常处理方法上面,括号里的类便是需要进行处理异常的类,在这里简单的使用Excpetion.class来进行演示。

@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public String onException(Exception e) {
        return e.getMessage();
    }
}

        2.4 TestController.class

@RestController
public class TestController {

    @GetMapping("/test")
    public void test() {
        throw new RuntimeException("出错啦!");
    }
}

        2.5 测试结果

        使用postman来进行测试,访问http://localhost:8080/test,可见,返回“出错啦”

        2.6 自定义异常返回

        这里以业务异常为例,创建BusinessException.class来代表业务异常,该类需要去继承RuntimeException类,并实现其构造方法

/**
 * @author anxin
 * @date 2022/3/29 22:38
 */
public class BusinessException extends RuntimeException{
    public BusinessException(String message) {
        super(message);
    }
}

        修改TestController.class文件,使其抛出BusinessException

/**
 * @author anxin
 * @date 2022/3/28 21:57
 */
@RestController
public class TestController {

    @GetMapping("/test")
    public void test() {
        throw new BusinessException("自定义异常!");
    }
}

        使用postman测试工具可以看到,返回值为“自定义异常”,可见自定义异常成功!

如果需要对全局异常处理的返回结果进行一个封装

可以查看:springboot统一返回结果封装_安心不心安的博客-CSDN博客

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安心不心安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值