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

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

相关推荐
zjshuster2 分钟前
墨西哥中央银行网联清算系统接入总结
java·财务对账
小锋java12343 分钟前
SpringBoot 4 + Spring Security 7 + Vue3 前后端分离项目设计最佳实践
java·vue.js·spring boot
一 乐3 分钟前
校园线上招聘|基于springboot + vue校园线上招聘系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·校园线上招聘系统
不懂的浪漫6 分钟前
mqtt-plus 架构解析(四):MqttMessageInterceptor 的扩展点设计
java·spring boot·物联网·mqtt
西海天际蔚蓝8 分钟前
AI配合写的第一个demo系统页面
java·人工智能
小旭952721 分钟前
Spring Security 实现权限控制(认证 + 授权全流程)
java·后端·spring
金銀銅鐵28 分钟前
[Java] 如何通过 cglib 的 FastClass 调用一个类中的“任意”方法?
java·后端
阿维的博客日记1 小时前
为什么会增加TreeMap和TreeSet这两类,有什么核心优势吗?可以解决什么核心痛点?
java·treeset·treemap
dllxhcjla1 小时前
黑马头条1
java
宠友信息1 小时前
一套基于uniapp+springboot完整社区系统是如何实现的?友猫社区源码级功能解析
java·spring boot·后端·微服务·微信·uni-app