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

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

相关推荐
无心水2 分钟前
Java时间处理封神篇:java.time全解析
java·开发语言·python·架构·localdate·java.time·java时间处理
wuyikeer6 分钟前
Spring BOOT 启动参数
java·spring boot·后端
多看书少吃饭14 分钟前
Vue + Java + Python 打造企业级 AI 知识库与任务分发系统(RAG架构全解析)
java·vue.js·笔记
博傅44 分钟前
Kubernetes (K8s) 入门到实战教程
java
奋斗的老史1 小时前
Stream-流式操作
java·windows
清风徐来QCQ1 小时前
八股文(1)
java·开发语言
zdl6861 小时前
springboot集成onlyoffice(部署+开发)
java·spring boot·后端
摇滚侠1 小时前
你是一名 java 程序员,总结定义数组的方式
java·开发语言·python
架构师沉默2 小时前
AI 让程序员更轻松了吗?
java·后端·架构
MrSYJ2 小时前
有没有人懂socketChannel中的write,read方法啊,给我讲讲
java·程序员·netty