[英]Get request values from ExceptionHandler using Spring MVC
我有一個 Spring MVC 控制器和一個異常處理程序。 發生異常時,我希望異常處理程序記錄請求中發送的所有 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 注入屬性,然后訪問異常處理程序中的值:
@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());
}
}
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.