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

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

相关推荐
怒放吧德德6 小时前
Spring Boot 实战:RSA+AES 接口全链路加解密(防篡改 / 防重放)
java·spring boot·后端
郑州光合科技余经理9 小时前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
大大水瓶10 小时前
Tomcat
java·tomcat
dustcell.10 小时前
haproxy七层代理
java·开发语言·前端
游离态指针10 小时前
以为发消息=下单成功?RabbitMQ从0到秒杀实战的完整踩坑笔记
java
BD_Marathon10 小时前
工厂方法模式
android·java·工厂方法模式
玹外之音11 小时前
Spring AI MCP 无状态服务器实战:构建AI智能用户管理系统
java·后端
java干货11 小时前
Redis 的 ZipList 是什么?它是怎么解决内存碎片问题的?
java
失重外太空啦11 小时前
Tomcat
java·服务器·tomcat
屎到临头想搅便11 小时前
TOMCAT
java·tomcat