gpt4 book ai didi

java - com.fasterxml.jackson.databind.JsonMappingException : No content to map due to end-of-input in Spring Boot App

转载 作者:太空宇宙 更新时间:2023-11-04 09:56:54 25 4
gpt4 key购买 nike

摘要:我从服务器应用程序向另一个端点发送请求。我收到 Http 401 错误响应。当我尝试将此错误主体映射到我的错误类时,我收到如下异常:

com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input

详细信息:我使用 Spring Boot 和 jackson-datatype-jsr310 开发一个服务器应用程序。我在向另一个服务器应用程序发送请求时使用 Spring 框架的 RestTemplate,例如:

public abstract class AbstractBackendAdapter {

@Autowired
private RestTemplate restTemplate;

@Autowired
private ObjectMapper mapper;

private <T> T exchange(final String url, final HttpMethod method, final HttpEntity request,
final Class<T> responseType) {

...

final ResponseEntity<T> response;

try {
response = restTemplate.exchange(url, method, request, responseType);
} catch (HttpServerErrorException exception) {
throw new BackendHttpServerException(exception, method, url, request.getHeaders());
} catch (HttpClientErrorException exception) {
throw new BackendHttpClientException(exception, method, url, request.getHeaders());
} catch (HttpMessageNotReadableException exception) {
throw new BackendHttpMessageNotReadableException(exception, method, url, request.getHeaders());
}
...
}

我不使用默认的 Spring 错误处理。相反,我编写了异常处理程序类,如下所示:

@RestControllerAdvice
public class RestResponseEntityExceptionHandler {

@Autowired
private ObjectMapper mapper;

@Autowired
private HttpServletRequest httpServletRequest;

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = {BackendHttpClientException.class})
@ResponseBody
protected ErrorResponse handleBackendClientException(final BackendHttpClientException exception,
final HttpServletResponse response) {

...

if (HttpStatus.BAD_REQUEST == httpStatus) {
...
} else if (HttpStatus.UNAUTHORIZED == httpStatus) {
final ClientErrorInfo error;

try {
error = mapper.readValue(exception.getResponseBodyAsString(), ClientErrorInfo.class);

final String errorCode = error.getErrorCode();

logBackendError(httpMethod, url, headers,
httpStatus, errorCode, error.getErrorMessage(), error.getErrorCause());

errorResponse = errorResponseConverter.prepareErrorResponse(errorCode, response);
} catch (IOException ioException) {
errorResponse = generateUnexpectedJsonFormatError(ioException);
}

}

return errorResponse;
}

但是,在某些情况下,我收到正文为空的 Http 401 响应。我的意思是,Exception.getResponseBodyAsString() 返回 null。因此,mapper.readValue(exception.getResponseBodyAsString(), ClientErrorInfo.class) 无法将 null 值解析为 ClientErrorInfo.class。然后,JsonMappingExcepiton 被抛出到行 - mapper.readValue(exception.getResponseBodyAsString(), ClientErrorInfo.class)。相关日志类似于:

com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
at [Source: ; line: 1, column: 0]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270)
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3854)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3799)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2858)
at com.commencis.butterfly.core.RestResponseEntityExceptionHandler.handleBackendClientException(RestResponseEntityExceptionHandler.java:145)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:384)
at org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:59)
at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:136)
at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:74)
at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1222)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1034)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:984)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:110)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:167)
at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:80)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

另一方面,当我通过 Postman 向同一端点发送相同的请求时,我收到带有填充正文的 Http 401 错误:

{
"errorCode": "ERR_C13",
"errorMessage": "Authorization failed",
"errorCause": "RETRIEVABLE_PNR_SR_CODE"
}

编辑1:通过使用 Charles,我在我的服务器应用程序和我向其发送请求的端点之间进行干预,并在我的服务器应用程序收到之前检查响应。响应类似于:

HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=C157382C48E***9972A77DADC; Path=/crane-ticketing; Secure; HttpOnly
Set-Cookie: rememberMe=deleteMe; Path=/crane-ticketing; Max-Age=0; Expires=Tue, 04-Dec-2018 13:38:02 GMT
Content-Type: application/json;charset=UTF-8
Content-Length: 100
Date: Wed, 05 Dec 2018 13:38:01 GMT
Connection: Keep-alive

{"errorCode":"ERR_C13","errorMessage":"Authorization failed","errorCause":"RETRIEVABLE_PNR_SR_CODE"}

EDIT-2: application.properties 中的一些 spring-jackson 配置行,例如:

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS = false
spring.jackson.serialization.FAIL_ON_EMPTY_BEANS = false
spring.jackson.deserialization.ADJUST_DATES_TO_CONTEXT_TIME_ZONE = false
spring.jackson.default-property-inclusion=NON_ABSENT
spring.jackson.mapper.AUTO_DETECT_GETTERS=false

如何在我的服务器应用程序中看到与 Postman 中的错误响应相同的带有填充正文的错误响应?任何想法将不胜感激!

最佳答案

经过一些调试,我意识到问题的原因是SimpleClientHttpResponse中的代码,它是Resttemplate的默认响应类。另外,我发现 Spring JIRA 中存在一些关于此问题的问题:

引用:https://jira.spring.io/browse/SPR-9367

“使用默认设置在 RestTemplate 中处理 401 响应非常困难(不可能)。事实上这是可能的,但您必须提供错误处理程序和请求工厂。错误处理程序很明显,但问题是默认请求工厂使用 java.net,当您尝试查看响应的状态代码时(尽管它显然可用),它可能会抛出 HttpRetryException。解决方案是使用 HttpComponentsClientHttpRequestFactory。”

当我在 POM 文件中添加下面编写的依赖项时,我的应用程序开始处理 401 响应的正文。

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>

关于java - com.fasterxml.jackson.databind.JsonMappingException : No content to map due to end-of-input in Spring Boot App,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54022183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com