SpringBoot捕获requestBody错误

时间:2017-04-26 18:52:35

标签: spring spring-boot

我有一个接受一些JSON的应用程序。它有一个带@RestController的控制器,然后是

@RequestMapping(value="/junk", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
public MyResponse postInfo(@RequestBody MyRequest info) {
...
}

这“工作”,因为它接受根据“MyRequest”对象有效的JSON并处理它。我有兴趣捕获JSON无效的时间。

目前当数据不好时会发生什么事情Spring似乎写了这样的东西到stdout:

2017-04-26 13:57:40.621  WARN 13537 --- [pr-8080-exec-13] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unexpected character ('}' (code 125)): was expecting double-quote to start field name
at [Source: java.io.PushbackInputStream@cc73b4; line: 1, column: 1048800]
at [Source: java.io.PushbackInputStream@cc73b4; line: 1, column: 1048796] (through reference chain: com.junk.ProcessInfo["process_list"]->java.util.ArrayList[4692]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('}' (code 125)): was expecting double-quote to start field name
at [Source: java.io.PushbackInputStream@cc73b4; line: 1, column: 1048800]
at [Source: java.io.PushbackInputStream@cc73b4; line: 1, column: 1048796] (through reference chain: com.junk.ProcessInfo["process_list"]->java.util.ArrayList[4692])

这一切都很好,但是我想知道请求是什么,所以我可以在源端修复它。

我正在玩“ControllerAdvisor”,如

@ControllerAdvice(annotations = RestController.class)
public class ControllerAdvisor {

    private static final Logger logger = LogManager.getLogger();

    @ModelAttribute
    public void logBody(HttpServletRequest request, HttpServletResponse response, @RequestBody String requestString) {
        logger.trace("requestString" + requestString);
    }
}

似乎写出了每个请求的请求体(不仅仅是错误),但是当我使用它时,它似乎修改了请求,使得实际的控制器将失败

2017-04-26 14:28:31.432  WARN 523 --- [io-8081-exec-29] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public com.junk.MyResponse com.junk.ProcessController.postInfo(com.junk.MyRequest)

我也在玩Actuator,但Actuator.trace实际上并没有给我身体。

有没有办法在RestController中获取实际的requestBody?

编辑:这是一个演示行为的完整应用程序:

Download example

1 个答案:

答案 0 :(得分:0)

从日志中可以看出,这不是服务器端实现的问题。从日志中我解释它,就像你发布了一个像这样的JSON主体:

{
    myPropert: myvalue
}
消息转换器期待

{
    "myPropert": "myvalue"
}