使用Spring MVC从ExceptionHandler获取请求值

我有一个Spring MVC Controller和一个Exception Handler。发生异常时,我希望异常处理程序记录请求中发送的所有GET /

POST数据。如何做到这一点?

控制器:

@Controller

@RequestMapping("/foo")

public class FooController {

private final FooService fooService;

@PostMapping("/bar")

@ResponseBody

public BarObject doSomething(@RequestBody final FooContext context)

{

return fooService.doSomething(context);

}

}

异常处理程序:

@ControllerAdvice

public class ExceptionController {

private final Logger log = LoggerFactory.getLogger(ExceptionController.class);

@ResponseStatus(HttpStatus.BAD_REQUEST)

@ExceptionHandler(Exception.class)

@ResponseBody

public ErrorMessage handleException(final HttpServletRequest request, final Exception exception) {

//Retrieve request data

//request.getQueryString()

// How to get POST data if we cannot access @RequestBody?)

log.error(request.getRequestURI(), exception);

return new ErrorMessage(request.getRequestURI(), exception.getLocalizedMessage());

}

回答:

好吧,请求主体位于HttpServletRequest中。

您可以通过执行以下操作来访问RAW请求正文:

String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));

从异常处理程序方法。(使用Java 8)。

然后,您可以将主体字符串解析为POJO。

注意,avobe答案无效。发生这种情况是因为在解析正文(使用@RequestBody)时,http连接流已关闭,因此无法再次访问请求正文。如何通过控制器方法将属性直接注入httpRequest,然后在Exception处理程序中访问值:

@RestController

@RequestMapping(ApiVersion.V1.prefix)

public class BatchController {

@PostMapping("/batch")

public @ResponseBody BatchResponse runBatch(@RequestBody BatchRequest batchRequest, HttpServletRequest request) throws IOException {

System.out.println(batchRequest.getName());

request.setAttribute("batchRequest" , batchRequest);

throw new IllegalArgumentException("Some error");

}

@ExceptionHandler(IllegalArgumentException.class)

public @ResponseBody BatchResponse handle(HttpServletRequest request) {

BatchRequest batchRequest = (BatchRequest) request.getAttribute("batchRequest");

System.out.println("handling exception");

return new BatchResponse(batchRequest.getName());

}

}

希望这可以帮助

以上是 使用Spring MVC从ExceptionHandler获取请求值 的全部内容, 来源链接: utcz.com/qa/432153.html

回到顶部