【问题标题】:Get request values from ExceptionHandler using Spring MVC使用 Spring MVC 从 ExceptionHandler 获取请求值
【发布时间】:2019-03-02 13:16:30
【问题描述】:

我有一个 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());
}

【问题讨论】:

    标签: java spring-mvc exception httprequest


    【解决方案1】:

    请求正文在 HttpServletRequest 中。

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

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

    来自异常处理方法。 (使用 java 8)。

    然后就可以将body字符串解析为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());
        }
    }
    

    希望对你有帮助

    【讨论】:

    • 当我在handleException 方法中调用request.getReader() 时出现IllegalStateException 异常:Controller$ErrorMessage com.foo.core.ExceptionController.handleException(javax.servlet.http.HttpServletRequest,java .lang.Exception) java.lang.IllegalStateException: 在 org.eclipse.jetty.server.Request.getReader(Request.java:1158) 流式传输
    猜你喜欢
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 2016-11-03
    • 2012-06-20
    • 1970-01-01
    相关资源
    最近更新 更多