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

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

相关推荐
能工智人小辰12 分钟前
二刷 苍穹外卖day10(含bug修改)
java·开发语言
DKPT13 分钟前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
缘来是庄15 分钟前
设计模式之外观模式
java·设计模式·外观模式
知其然亦知其所以然1 小时前
JVM社招面试题:队列和栈是什么?有什么区别?我在面试现场讲了个故事…
java·后端·面试
harmful_sheep1 小时前
Spring 为何需要三级缓存解决循环依赖,而不是二级缓存
java·spring·缓存
星辰大海的精灵1 小时前
如何确保全球数据管道中的跨时区数据完整性和一致性
java·后端·架构
大大。1 小时前
van-tabbar-item选中active数据变了,图标没变
java·服务器·前端
nc_kai1 小时前
Flutter 之 每日翻译 PreferredSizeWidget
java·前端·flutter
Codebee1 小时前
OneCode:AI时代的先锋——注解驱动技术引领开发范式变革
java
勤奋的知更鸟1 小时前
Java 编程之状态模式
java·开发语言·状态模式