当前位置: 首页 > article >正文

SpringBoot 自定义异常处理

自定义异常处理可以帮助我们更好地管理应用程序中的异常,并返回统一的错误响应。

1. 自定义异常类

定义自己的异常类,继承自 RuntimeException 或其他异常类。

public class MyException extends RuntimeException {
    private String msg;
    public MyException(String msg) {
        super(msg);
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

2. 使用 @ControllerAdvice 和 @ExceptionHandler

@ControllerAdvice 是一个全局的异常处理类,它可以处理整个应用程序中抛出的异常。@ExceptionHandler 用于指定处理特定异常的方法。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(MyException.class)
    public ResponseEntity<String> MyExceptionHandle(Exception e){
        return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> exceptionHandle(Exception e){
        e.printStackTrace();
        return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

3. 创建控制器类,在 Controller 中抛出异常

import com.qvtu.web.exception.MyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/dish")
public class DishController {
    @RequestMapping("/del/{i}")
    public ResponseEntity<String> delDish(@PathVariable String i) {
        Integer id=Integer.valueOf(i);
        if (id<0){
            throw  new MyException("参数错误!");
        }
        return new ResponseEntity<>("del success", HttpStatus.OK);
    }
}

4. 运行测试

启动程序,在浏览器中访问http://localhost:8080/dish/del/1
在这里插入图片描述
在浏览器中访问http://localhost:8080/dish/del/-1
在这里插入图片描述
在浏览器中访问http://localhost:8080/dish/del/a
在这里插入图片描述


http://www.kler.cn/a/579508.html

相关文章:

  • SparkAi系统体验
  • 【最后203篇系列】011 Mongo异步代理开发回顾
  • golang 从零单排 (一) 安装环境
  • 京东POP商家小程序电商布局策略与优化路径研究
  • 《Python实战进阶》No17: 数据库连接与 ORM(SQLAlchemy 实战)
  • 从零开始的 Kafka 学习(二)| 集群启动
  • vue+element|el-tree树设置懒加载和设置默认勾选
  • Go_zero学习笔记
  • 关于更新字段为空值——MybatisPlus框架
  • Linux | Vim 鼠标不能右键粘贴、跨系统复制粘贴
  • 为企业级AI交互系统OpenWebUI集成LDAP用户权限认证(1)
  • Python爬虫实战:爬取财金网实时财经信息
  • 如何高效准备PostgreSQL认证考试?
  • 基于LabVIEW的脚本化子VI动态生成
  • 如何构建一个 Docker 镜像?
  • 汇编点亮LED
  • 假设检验与置信区间在机器学习中的应用
  • 【Linux】信号处理以及补充知识
  • c++: 容器vector
  • 对WebSocket做一点简单的理解