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

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
在这里插入图片描述

相关文章:

  • 【HarmonyOS Next】鸿蒙加固方案调研和分析
  • 祝福语【算法赛】
  • ESP32驱动OV3660摄像头实现物体轮廓识别(摄像头支持红外夜视、边缘AI计算)
  • C++常用函数
  • SpringBoot统一响应类型3.1.1版本
  • 初识大模型——大语言模型 LLMBook 学习(一)
  • 计算机网络传输层
  • 电子学会—2024年月6青少年软件编程(图形化)四级等级考试真题——水仙花数
  • Python 动态规划(DP)套路总结
  • UE5从入门到精通之如何创建自定义插件
  • (数据结构)双向链表
  • 2025-03-09 学习记录--C/C++-PTA 习题11-1 输出月份英文名
  • BEVDepth: Acquisition of Reliable Depth for Multi-view 3D Object Detection 论文阅读
  • 代码随想录算法训练营第八天|Leetcode 151.翻转字符串里的单词 卡码网:55.右旋转字符串 字符串总结 双指针回顾
  • 基于Spring3的抽奖系统
  • 通义千问:Qwen2.5-0.5B模型架构解释
  • 绘制列线图并解释线性模型的Python包-nomogram-explainer(记我的第一个pypi项目)
  • 配置多区域OSPF,配置OSPF手动汇总,配置OSPF特殊区域
  • IO多路复用实现并发服务器
  • 电路研究10——MPU6050电路搭建
  • 滨湖区知名做网站选哪家/优化落实防控措施
  • 网站站建设建技设术技术/怎么进行推广
  • 大型集团网站建设/优化方案模板
  • the7.3 wordpress/windows优化工具
  • 邮轮哪个网站是可以做特价胃肠的/怎么做一个免费的网站
  • 工程造价定额在哪查/兰州网络推广关键词优化