全局异常统一处理方案
一、依赖引入
<dependency>
<groupId>org.zalando</groupId>
<artifactId>problem-spring-web</artifactId>
<version>0.26.1</version>
</dependency>
使用下面的
<dependency>
<groupId>org.zalando</groupId>
<artifactId>problem-spring-web-starter</artifactId>
<version>0.26.1</version>
</dependency>
二、配置两个ExceptionHandler
2.1、ExceptionHandling
package com.moss.uaa_security.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.zalando.problem.spring.web.advice.ProblemHandling;
/**
* @description
* @author: lwj
* @create: 2021-03-25 23:34
**/
@ControllerAdvice
public class ExceptionHandling implements ProblemHandling {
/**
* 是否将堆栈中的错误信息返回
*
* @return
*/
@Override
public boolean isCausalChainsEnabled() {
return true;
}
}
2.2、SecurityExceptionHandler
package com.moss.uaa_security.exception;
import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;
/**
* @description
* @author: lwj
* @create: 2021-03-25 23:36
**/
public class SecurityExceptionHandler implements SecurityAdviceTrait {
}
三、配置使用zalando的problem处理security的请求异常
四、中文乱码处理
如果在测试中发现出现中文乱码,则配置下面servlet.encoding.force: true
server:
error:
whitelabel:
enabled: true
servlet:
encoding:
force: true
五、全局异常处理
package com.nis.charge.exception;
import com.nis.charge.constant.ErrorConstants;
import com.nis.charge.exception.problem.BusinessErrorProblem;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.NativeWebRequest;
import org.zalando.problem.DefaultProblem;
import org.zalando.problem.Problem;
import org.zalando.problem.ProblemBuilder;
import org.zalando.problem.Status;
import org.zalando.problem.spring.web.advice.ProblemHandling;
import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;
import org.zalando.problem.violations.ConstraintViolationProblem;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
/**
* 全局异常处理
*
* @author lwj
*/
@ControllerAdvice
public class ExceptionHandling implements ProblemHandling, SecurityAdviceTrait {
@Override
public boolean isCausalChainsEnabled() {
return false;
}
@Override
public void log(Throwable throwable, Problem problem, NativeWebRequest request, HttpStatus status) {
ProblemHandling.super.log(throwable, problem, request, status);
// TODO 记录异常请求信息
System.out.println("###############ExceptionHandler############");
}
/**
* Post-process Problem payload to add the message key for front-end if needed
*/
@Override
public ResponseEntity<Problem> process(@Nullable ResponseEntity<Problem> entity, NativeWebRequest request) {
if (entity == null || entity.getBody() == null) {
return entity;
}
Problem problem = entity.getBody();
if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) {
return entity;
}
ProblemBuilder builder = Problem.builder()
.withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType())
.withStatus(problem.getStatus())
.withTitle(problem.getTitle())
.with("path", request.getNativeRequest(HttpServletRequest.class).getRequestURI());
if (problem instanceof ConstraintViolationProblem) {
builder
.with("violations", ((ConstraintViolationProblem) problem).getViolations())
.with("message", ErrorConstants.ERR_VALIDATION);
return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode());
} else {
builder
.withCause(((DefaultProblem) problem).getCause())
.withDetail(problem.getDetail())
.withInstance(problem.getInstance());
problem.getParameters().forEach(builder::with);
if (!problem.getParameters().containsKey("message") && problem.getStatus() != null) {
builder.with("message", "error.http." + problem.getStatus().getStatusCode());
}
return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode());
}
}
/**
* 处理自定义业务异常
*
* @param ex
* @param request
* @return
*/
@ExceptionHandler(BusinessErrorProblem.class)
public ResponseEntity<Problem> handleBusinessErrorException(BusinessErrorProblem ex, NativeWebRequest request) {
return ResponseEntity.status(Status.OK.getStatusCode()).body(Problem.builder()
.withDetail(ex.getDetail())
.withStatus(Status.INTERNAL_SERVER_ERROR)
.withTitle(Status.UNAUTHORIZED.getReasonPhrase())
.build());
}
}
六、测试
6.1、模拟业务异常
6.2、模拟代码执行异常
七、各类异常记录
7.1、用户登陆,账号密码错误
7.2、后台接口入参校验
7.3、401需要登录
指用户没有登陆的情况下访问资源
7.3、402 refreshToken失效
7.4、403无访问权限
指用户登录后访问,用户没有权限访问的资源。