如何在@ExceptionHandler方法中检索POST请求对象/参数

时间:2019-09-27 18:37:46

标签: spring rest

我有一个controllerAdvice / @ ExceptionHandler方法。我需要在ExceptionHandler方法中访问我的Request参数。 我可以使用getRequestURI()检索URI,但不知道如何检索POST请求参数 我有一些标识符参数,必须通过ExceptionResponse发送回去。我该怎么办?

    @ExceptionHandler(HttpClientErrorException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public @ResponseBody MyResponse handleResourceNotFound(final HttpClientErrorException ex,
            final HttpServletRequest request) {
        String str = request.getRequestURI();
        System.out.println(str);
        MyResponse response = new MyResponse(ex.getResponseBodyAsString(), 0, "-1");
        return response;
    }

1 个答案:

答案 0 :(得分:0)

对此没有直接的方法。就我而言,我确实喜欢以下内容。

控制器

@PostMapping("/test/")
@ResponseBody
public boolean isExist(@RequestBody Person person, HttpServletRequest request) {
    request.setAttribute("requestBody", person);
    int i = 1/0;
    return person != null && person.isExist();
}

异常处理程序

@ExceptionHandler(HttpClientErrorException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public @ResponseBody MyResponse handleResourceNotFound(final HttpClientErrorException ex,
        final HttpServletRequest request) {
    String str = request.getRequestURI();
    System.out.println(request.getAttribute("requestBody"));
    MyResponse response = new MyResponse(ex.getResponseBodyAsString(), 0, "-1");
    return response;
}