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

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

相关推荐
月明长歌3 分钟前
【码道初阶】【LeetCode 160】相交链表:让跑者“起跑线对齐”的智慧
java·算法·leetcode·链表
菜鸟小芯6 分钟前
OpenHarmony环境搭建——02-JDK17安装教程
java
原来是好奇心20 分钟前
深入Spring Boot源码(二):启动过程深度剖析
java·源码·springboot
听风吟丶21 分钟前
Spring Boot 自动配置原理深度解析与实战
java·spring boot·后端
原来是好奇心21 分钟前
深入Spring Boot源码(一):环境搭建与初探项目架构
java·gradle·源码·springboot
韩凡22 分钟前
JAVA微服务与分布式(概念版)
java·分布式·微服务
bing.shao23 分钟前
Golang 之闭包
java·算法·golang
济南壹软网络科技有限公司25 分钟前
下一代盲盒系统核心架构解析:JAVA-S1如何打造极致公平与全球化体验
java·开源·盲盒源码·盲盒h5·国际盲盒源码
qq_3363139333 分钟前
HashMap
java·开发语言