简体   繁体   English

如何在HTTP异常处理期间从请求中获取POST正文?

[英]how to get POST body from request during http exception handling?

I have 2 microservices. 我有2个微服务。 1 of them sends a request to 2, 2 microservice throws an exception and adds new addition field errors to response with useful data: 其中1个向2发送请求,2个微服务引发异常并添加新的加法字段错误以响应有用数据:

    public static class ErrorResponse  {
        private Integer status;
        private String transactionId;
        private String sessionId;
        private String message;
        private List<FieldError> errors;
    //....setters/getters
    }

{
    "status": 400,
    "message": "Validation failed for object='x'. Error count: 1",
    "sessionId": "",
    "transactionId": "xxx",
    "errors": [
        {
            "codes": [
                ""
            ],
            "arguments": null,
            "defaultMessage": null,
            "objectName": "",
            "field": "",
            "rejectedValue": 0,
            "bindingFailure": false,
            "code": "invalid value"
        }
    ]
}

in 1 microservice I have a global exception handler which sends it on client, but the problem is that I can't get the filed errors from HttpServletRequest . 在1个微服务中,我有一个全局异常处理程序,该异常处理程序在客户端上发送该异常处理程序,但是问题是我无法从HttpServletRequest中获取已归档的错误 getReader() method throws another exception. getReader()方法引发另一个异常。 And as result client gets 结果客户得到了

{
    "status": 400,
    "message": "Validation failed for object='x'. Error count: 1",
    "sessionId": "",
    "transactionId": "xxx",
    "errors": null
}

You can't call getReader a second time. 您不能再次调用getReader。 This link explains why: resetting a HttpRequest after calling request.getReader() . 该链接说明了原因: 在调用request.getReader()之后重置HttpRequest You can pass this information through a thread local if its something globally used through the application. 如果该信息在应用程序中全局使用,则可以通过本地线程传递此信息。 You would need to make sure to reset the thread local appropriately. 您需要确保适当地在本地重置线程。 You could also catch the previous exception, wrap it in a custom exception class, and put this information inside of your custom exception. 您还可以捕获先前的异常,将其包装在自定义异常类中,然后将此信息放入自定义异常中。 Then you can throw your custom exception that has the information you need. 然后,您可以抛出具有所需信息的自定义异常。

the solution is to implement ErrorDecoder interface and override 解决方案是实现ErrorDecoder接口并覆盖

@Override
Exception decode(String methodKey, Response response) {
    // response has getBody() method to get all data from a request 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM