spring系列之-异常统一处理(1)

本文介绍了在开发过程中统一API返回格式的重要性,并通过引入特定的jar包实现了一致性的响应结构。该方法有助于前后端联调及第三方接口对接,通过示例代码展示了如何配置全局异常处理及安全相关异常。

前言

为什么需要这个东西,因为我们在开发接口不管是与前端联调,或者是与第三方对接,对方都需要很清楚的知道你的返回是怎么样的,对方才能进行参数的解析工作。所以统一返回十分的有必要,这种方式了只是其一,还有另外的方式,我有时间,有机会就整理,没有就用这篇即可。

Jar包引入

<dependency>
   <groupId>org.zalando</groupId>
   <artifactId>problem-spring-web</artifactId>
   <version>0.26.1</version>
</dependency>

代码

  • 全局异常类
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.zalando.problem.spring.web.advice.ProblemHandling;

@ControllerAdvice
public class ExceptionHandler implements ProblemHandling
{
    /**
     * 是否打印堆栈信息
     * @return
     */
    @Override
    public boolean isCausalChainsEnabled()
    {
        return true;
    }
}
  • 安全用
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;

@ControllerAdvice
public class SecurityExceptionHandler implements SecurityAdviceTrait {}
  • 集成

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值