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

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

相关推荐
2601_949814495 分钟前
Spring Boot中使用Server-Sent Events (SSE) 实现实时数据推送教程
java·spring boot·后端
splage15 分钟前
HeidiSQL导入与导出数据
java
热爱Java,热爱生活19 分钟前
浅谈Spring三级缓存
java·spring·缓存
@ chen31 分钟前
IDEA初始化配置
java·ide·intellij-idea
wellc1 小时前
SpringBoot集成Flowable
java·spring boot·后端
Hui Baby2 小时前
springAi+MCP三种
java
hsjcjh2 小时前
【MySQL】C# 连接MySQL
java
敖正炀2 小时前
LinkedBlockingDeque详解
java
wangyadong3172 小时前
datagrip 链接mysql 报错
java
untE EADO2 小时前
Tomcat的server.xml配置详解
xml·java·tomcat