Spring RestTemplate:错误响应体转POJO及空响应兼容方案
RestTemplate异常响应解析容错处理方案
问题场景
我编写了一个用于调用其他REST服务的辅助方法,代码如下:
public BaseResponse doPostService(String url, Object body) throws Exception { RestTemplate rest = new RestTemplate(); try { ResponseEntity<BaseResponse> r = rest.postForEntity(url, body, BaseResponse.class); return r.getBody(); } catch (RestClientResponseException e) { ObjectMapper mapper = new ObjectMapper(); // 我想返回这里捕获的响应体 return mapper.readValue(e.getResponseBodyAsString(), BaseResponse.class); } catch (ResourceAccessException e) { e.printStackTrace(); throw new Exception(e.getMessage()); } }
遇到的问题:当e.getResponseBodyAsString()的结果无法解析为BaseResponse类时会报错,需要无需新增方法的解决技巧。
可行解决技巧
1. 给解析逻辑加局部兜底try-catch
在RestClientResponseException的捕获块内,对JSON解析代码再加一层异常捕获,解析失败时返回预设的错误响应实例:
catch (RestClientResponseException e) { ObjectMapper mapper = new ObjectMapper(); try { return mapper.readValue(e.getResponseBodyAsString(), BaseResponse.class); } catch (JsonProcessingException parseEx) { // 构造解析失败的响应 BaseResponse fallbackResp = new BaseResponse(); fallbackResp.setCode("PARSE_FAILED"); fallbackResp.setMessage("响应体解析错误: " + parseEx.getMessage()); return fallbackResp; } }
2. 配置ObjectMapper的容错特性
通过配置ObjectMapper的反序列化参数,降低解析的严格性,减少解析失败的概率,再配合兜底捕获:
catch (RestClientResponseException e) { ObjectMapper mapper = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, false) .configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); try { return mapper.readValue(e.getResponseBodyAsString(), BaseResponse.class); } catch (JsonProcessingException parseEx) { return new BaseResponse(); // 最终兜底返回空实例 } }
3. 忽略解析异常返回默认实例
如果不需要错误响应的具体内容,直接忽略所有解析异常,返回一个默认的BaseResponse实例:
catch (RestClientResponseException e) { ObjectMapper mapper = new ObjectMapper(); try { return mapper.readValue(e.getResponseBodyAsString(), BaseResponse.class); } catch (Exception ignore) { return new BaseResponse(); } }
内容的提问来源于stack exchange,提问作者Dhana D.
相关产品推荐
相关产品推荐

