springboot项目中统一异常处理 UnifyResponse

本文详细介绍了在SpringBoot项目中如何实现统一异常处理,通过创建`GlobalExceptionAdvice`类拦截并封装异常为`UnifyResponse`。异常分为CheckedException和RuntimeException。`UnifyResponse`的message部分避免硬编码,采用配置文件`exception-code.properties`存储错误代码和对应信息,并通过`ExceptionCodeConfiguration`类加载这些配置。示例代码展示了具体实现过程。
摘要由CSDN通过智能技术生成

响应格式:

json: 
	{
   
		code: 100001, #  错误码
		message: 未找到首页优惠券活动, # 错误信息
		request: GET url # 请求方式、请求url
	}

解决思路: 将异常拦截,然后封装成统一的格式(即类: UnifyResponse)

核心处理类:GlobalExceptionAdvice

 @ControllerAdvice
 public class GlobalExceptionAdvice{
   
 	@Autowired
 	private ExceptionCodeConfiguration codeConfiguration;
	// 对HttpException异常进行处理
	@ExceptionHandler(value = HttpException.class)
	public ResponseEntity<UnfiyResponse> handleHttpException(HttpServerletRequest req, HttpException e){
   
		// 请求url
		String requestUrl = req.getRequestURI();
		// 请求方法
		String method 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值