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

@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("对不起,您的操作有问题");

相关推荐
LSL666_3 小时前
MybatisPlus条件构造器(上)
java·数据库·mysql·mybatisplus
U-52184F693 小时前
深入理解“隐式共享”与“写时复制”:从性能魔法到内存深坑
java·数据库·算法
bearpping3 小时前
SpringBoot最佳实践之 - 使用AOP记录操作日志
java·spring boot·后端
一叶飘零_sweeeet3 小时前
线上故障零扩散:全链路监控、智能告警与应急响应 SOP 完整落地指南
java·后端·spring
Skilce3 小时前
ZrLog 博客系统部署指南(无 War 包版,Maven 构建 + 阿里云镜像优化)
java·阿里云·maven
敲代码的嘎仔3 小时前
Java后端开发——真实面试汇总(持续更新)
java·开发语言·程序人生·面试·职场和发展·八股
迈巴赫车主4 小时前
蓝桥杯20560逃离高塔
java·开发语言·数据结构·算法·职场和发展·蓝桥杯
泯仲4 小时前
Ragent项目7种设计模式深度解析:从源码看设计模式落地实践
java·算法·设计模式·agent
wangchunting4 小时前
Jvm-垃圾收集器
java·开发语言·jvm
weixin_464307634 小时前
QT智能指针
java·数据库·qt