# 一、依赖引入

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

# 二、配置两个ExceptionHandler

# ExceptionHandler

package com.moss.uaa_security.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.zalando.problem.spring.web.advice.ProblemHandling;


@ControllerAdvice
public class ExceptionHandler implements ProblemHandling {

    /**
     * 是否将堆栈中的错误信息返回
     */
    @Override
    public boolean isCausalChainsEnabled() {
        return true;
    }
}

# SecurityExceptionHandler

package com.moss.uaa_security.exception;

import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait;

public class SecurityExceptionHandler implements SecurityAdviceTrait {
}

# 三、配置使用zalando的problem处理security的请求异常

@RequiredArgsConstructor
@EnableWebSecurity(debug = true)
@Import(SecurityProblemSupport.class)
@Order(90)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final SecurityProblemSupport securityProblemSupport;
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .exceptionHandling(exceptionHandler ->
                        exceptionHandler
                                .authenticationEntryPoint(securityProblemSupport)// 认证失败
                                .accessDeniedHandler(securityProblemSupport)// 访问拒绝,无权限
                )
        ;
    }
}

# 四、中文乱码处理

如果在测试中发现出现中文乱码,则配置下面servlet.encoding.force: true

server:
  error:
    whitelabel:
      enabled: true
  servlet:
    encoding:
      force: true