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();	
	}
}

测试结果


相关推荐
Hx_Ma1614 分钟前
SpringMVC返回值
java·开发语言·servlet
Yana.nice18 分钟前
openssl将证书从p7b转换为crt格式
java·linux
独自破碎E21 分钟前
【滑动窗口+字符计数数组】LCR_014_字符串的排列
android·java·开发语言
想逃离铁厂的老铁24 分钟前
Day55 >> 并查集理论基础 + 107、寻找存在的路线
java·服务器
Jack_David30 分钟前
Java如何生成Jwt之使用Hutool实现Jwt
java·开发语言·jwt
瑞雪兆丰年兮32 分钟前
[从0开始学Java|第六天]Java方法
java·开发语言
一点技术1 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
datalover1 小时前
CompletableFuture 使用示例
java·开发语言
shuair1 小时前
redis实现布隆过滤器
spring boot·redis·bootstrap
RANCE_atttackkk1 小时前
Springboot+langchain4j的RAG检索增强生成
java·开发语言·spring boot·后端·spring·ai·ai编程