SpringBoot全局异常报错处理和信息返回

信息返回类

这种设计可以统一API返回格式,便于前端处理,也便于日志记录和错误排查

java 复制代码
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> 
{
	Integer code;
	String mes;
	T data;
	
	public static Result success()
	{
		return new Result(200,"成功",null);
	}

	public static Result error()
	{
		return new Result(500,"服务器出现未知错误",null);
	}

	public static Result error(String mes)
	{
		return new Result(500,mes,null);
	}
}

全局异常处理

全局异常处理可以统一管理异常,避免在每个 Controller 中重复处理异常

自定义异常类

java 复制代码
public class MyCustomException extends Exception 
{
	//构造方法
	public MyCustomException(String message) {
		super(message);
	}
}

全局异常处理类

java 复制代码
@ControllerAdvice
public class GlobalExceptionHandler
{
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handleException(Exception e)
    {
        //处理自定义异常信息
        if(e instanceof MyCustomException)
        {
            //将自定义异常进行转换
            MyCustomException myCustomException = (MyCustomException)e;
            return Result.error(myCustomException.getMessage());
        }
        //所有异常处理
        return Result.error(e.getMessage());
    }
}

控制层

java 复制代码
@RestController
@RequestMapping("demo")
public class DemoController 
{
	@GetMapping("getMyCustomException")
	public String getMyCustomException() throws Exception 
	{
		throw new MyCustomException("自定义报错信息");
	}
	
	@GetMapping("getException")
	public String getException() throws Exception
	{
		throw new Exception();	
	}
}

测试结果


相关推荐
zl9798991 分钟前
SpringBoot-Web开发之请求参数处理
java·spring boot
新建文件夹-7 分钟前
深入浅出Langchain4j——构建Java大语言模型应用的新范式
java·开发语言·语言模型
絔宝9 分钟前
Eclipse控制台乱码解决方式
java·ide·eclipse
xuejianxinokok27 分钟前
io_uring 快吗? Postgres 17 与 18 的基准测试
数据库·后端·postgresql
小白银子30 分钟前
零基础从头教学Linux(Day 55)
java·linux·服务器·python
DokiDoki之父31 分钟前
SpringMVC—REST风格 & Restful入门案例 & 拦截器简介 & 拦截器入门案例 & 拦截器参数 & 拦截器链配置
后端·restful
JohnYan42 分钟前
安全密钥(Security Key)和认证技术相关词汇表
后端·安全·设计模式
北海道浪子1 小时前
[免费送$1000]ClaudeCode、Codex等AI模型在开发中的使用
前端·人工智能·后端
不爱编程的小九九1 小时前
小九源码-springboot097-java付费自习室管理系统
java·开发语言·spring boot
兜兜风d'1 小时前
Spring Boot 整合 RabbitMQ :四大核心模式解析
spring boot·rabbitmq·java-rabbitmq