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