use of com.github.df.restypass.exception.execute.RequestException in project RestyPass by darren-fu.
the class ResponseConverterContext method convertResponse.
/**
* Convert response object.
*
* @param restyCommand the resty command
* @param response the response
* @return the object
*/
public Object convertResponse(RestyCommand restyCommand, Response response) {
Object result = null;
// response 为null
if (response == null) {
log.warn("response is null,command:{}", restyCommand);
restyCommand.failed(new ServerException("Failed to get response, it's null"));
return result;
}
// response为FailedResponse, [connectException InterruptedException] status 500
if (FailedResponse.isFailedResponse(response)) {
log.warn("response is failed by exception:{}", FailedResponse.class.cast(response).getException().getMessage(), FailedResponse.class.cast(response).getException());
restyCommand.failed(FailedResponse.class.cast(response).getException());
return result;
}
// 服务响应了请求,但是不是200
int statusCode = response.getStatusCode();
if (200 != statusCode) {
if (statusCode >= 400 && statusCode < 500) {
restyCommand.failed(new RequestException("Request: " + restyCommand + "; Response: " + response.toString()));
} else if (statusCode >= 500) {
restyCommand.failed(new ServerException("Request: " + restyCommand + "; Response: " + response.toString()));
}
log.warn("request is bad,status code:{},request:{},response:{}", statusCode, restyCommand, response);
return result;
}
byte[] body = response.getResponseBodyAsBytes();
// 使用转换器 转换响应结果 json->object
boolean converted = false;
Type returnType = restyCommand.getReturnType();
String respContentType = response.getContentType();
for (ResponseConverter converter : converterList) {
if (converter.support(returnType, respContentType)) {
converted = true;
result = converter.convert(body, returnType, respContentType);
break;
}
}
if (!converted) {
restyCommand.failed(new RestyException("没有合适的解析器,content-type:" + respContentType + ";body:" + response.getResponseBody()));
log.warn("没有合适的解析器,content-type:{};body:{}", respContentType, response.getResponseBody());
}
restyCommand.success();
return result;
}
Aggregations