摘要::我从服务器应用程序向另一个端点发送了一个请求。我收到Http 401错误响应。当我尝试将此错误主体映射到我的错误类时,出现类似以下的异常:
com.fasterxml.jackson.databind.JsonMappingException:没有要映射的内容 由于输入结束
详细信息::我使用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"
}
EDIT-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中的错误响应相同的错误响应?任何想法将不胜感激!
答案 0 :(得分:0)
进行一些调试之后,我意识到问题的原因是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>