【发布时间】:2019-11-20 00:17:39
【问题描述】:
我使用 Spring Boot 应用程序调用的服务根据 Http GET 请求成功或异常返回两种不同的对象类型。成功时返回“MyClass”对象,出现异常时返回“ErrorResponse”对象。我想知道如果它是正确的方式,我实现它的方式。
public class MyClass{
public ErrorResponse errorResponse;
//and some other fields here
}
@JsonIgnoreProperties
public class ErrorResponse {
@JsonProperty("error")
public Error error;
@JsonProperty("version")
public String version;
}
public class Error {
@JsonProperty("code")
public String Code;
@JsonProperty("message")
public String Message;
}
我得到的错误响应方式是
{
"error": {
"code": "invalidEntry",
"message": "The request you are making is invalid, please check your request data"
},
"version": "2.1.1"
}
而我的实现如下:
HttpEntity<MyClass> entity = new HttpEntity<MyClass>(headers);
ResponseEntity<MyClass> response = new ResponseEntity<MyClass>(HttpStatus.OK);
try {
response = restTemplate.exchange(url, HttpMethod.GET, entity, MyClass.class);
} catch (HttpClientErrorException ex) {
String responseBody = ex.getResponseBodyAsString();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
ErrorResponse errorResponse = mapper.readValue(responseBody, ErrorResponse.class);
MyClass myClass = new MyClass();
myClass.errorResponse = errorResponse;
return myClass;
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response.getBody();
【问题讨论】:
-
对于这个
I wanted to know that if it is the right way, the way I implemented it是的,但你可以使用baeldung.com/exception-handling-for-rest-with-spring
标签: java spring-boot exception