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

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

相关推荐
笃行客从不躺平1 小时前
接口幂等性(Idempotency)
java
Hero | 柒1 小时前
JAVA反射机制
java·spring·反射
j***63082 小时前
Springboot项目中线程池使用整理
java·spring boot·后端
likuolei2 小时前
Eclipse 创建 Java 接口
java·数据库·eclipse
q***54752 小时前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式
a***56062 小时前
Spring Boot接收参数的19种方式
java·spring boot·后端
z***75152 小时前
SpringBoot集成MQTT客户端
java·spring boot·后端
q***69772 小时前
java进阶1——JVM
java·开发语言·jvm
码力码力我爱你2 小时前
C++静态变量依赖关系
java·jvm·c++
q***76663 小时前
Java_ElasticSearch(ES)——分布式搜索引擎
java·elasticsearch·搜索引擎