Java 当尝试在springboot API中发布时,如何将请求的有效负载详细信息记录在401未经授权的错误上

Java 当尝试在springboot API中发布时,如何将请求的有效负载详细信息记录在401未经授权的错误上,java,spring-boot,http-status-code-401,Java,Spring Boot,Http Status Code 401,我有一种情况,当POST请求出现错误时,我需要知道请求的有效负载详细信息。 我认为,由于未经授权的错误,当请求没有发送到API端点时,我们将无法捕获有效负载。在命中此端点之前,它将被过滤掉 我使用的是Springboot 2.1.6 我的控制器方法如下 @PostMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<PayloadRespo

我有一种情况,当POST请求出现错误时,我需要知道请求的有效负载详细信息。 我认为,由于未经授权的错误,当请求没有发送到API端点时,我们将无法捕获有效负载。在命中此端点之前,它将被过滤掉

我使用的是Springboot 2.1.6

我的控制器方法如下

@PostMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<PayloadResponse> processPayload(@RequestBody String payload) {
    logger.info("Received a payload: {}", payload);
}
@PostMapping(value=“/users”,products=MediaType.APPLICATION\u JSON\u value)
公共响应属性processPayload(@RequestBody字符串负载){
info(“收到有效载荷:{}”,有效载荷);
}
有没有什么方法可以记录这个负载,甚至401错误?
提前感谢

您不能使用任何SpringMVC机制来捕获和记录此类错误,因为它发生在进入MVC堆栈之前@ControllerAdvice什么也做不了

您可以扩展
AuthenticationEntryPoint
并通过

@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

   protected void configure(HttpSecurity http) throws Exception {

        http.exceptionHandling()
                    .authenticationEntryPoint(new CustomAuthenticationEntryPoint())

    }
}

像这样延伸

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest req, HttpServletResponse res,
                         AuthenticationException authException)
            throws IOException {

        res.setContentType("application/json;charset=UTF-8");
        res.setStatus(401);
        res.getWriter().write(JsonUtil.getWriteMapper().writeValueAsString(
                new ErrorRestResponse(authException,false,""))); //This is my custom error response
        
        // You can put logging code around here

    }
}
您可以使用来处理各种请求,并读取它们的有效负载(如果提供的话),然后返回相应的响应