全局异常统一处理方案(zalando)

一、依赖引入

 		<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无访问权限

指用户登录后访问,用户没有权限访问的资源。
在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值