后端异常处理:全局异常处理器

@RestControllerAdvice=@ControllerAdvice+@ResponseBody

@ExceptionHandler(Exception.class)

java 复制代码
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

@ControllerAdvice
@RestController
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        // 这里可以根据实际需求定制异常处理逻辑
        return ResponseEntity.status(500).body("发生了未知错误: " + e.getMessage());
    }

    @ExceptionHandler(YourCustomException.class)
    public ResponseEntity<String> handleYourCustomException(YourCustomException e) {
        // 这里可以根据实际需求定制自定义异常处理逻辑
        return ResponseEntity.status(400).body("发生了自定义异常: " + e.getMessage());
    }

    // 可以添加更多的异常处理方法来处理不同类型的异常

}

如果有Result标准返回类可以return Result.error("对不起,您的操作有问题");

相关推荐
CODE202203181 分钟前
promptfoo自定义prompt生成器
java·前端·prompt
_waylau5 分钟前
“Java+AI全栈工程师”问答02:Spring Boot 自动配置原理
java·开发语言·spring boot·后端·spring
JAVA面经实录9175 分钟前
Java架构师最终完整版学习路线图
java·开发语言·学习
上海蓝色星球7 分钟前
从工具到资产:CER V2.0 造价机器人如何重构企业核心竞争力
java·数据库·mysql
spencer_tseng7 分钟前
System2.java
java·system
222you10 分钟前
Claude Code接入DeepSeek-v4模型
java·服务器·前端
i220818 Faiz Ul12 分钟前
高校教务|教务管理|基于springboot+vue的高校教务管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·高校教务系统
Ting-yu14 分钟前
SpringCloud快速入门(4)---- nacos安装与使用
java·spring·spring cloud
木子墨51614 分钟前
工程算法实战 | 从LRU到手写本地缓存:LinkedHashMap → 双向链表+哈希表 → Caffeine 原理
java·数据结构·算法·链表·缓存
无尽冬.20 分钟前
个人八股之三层架构
java·经验分享·后端·架构·异世界