1. restTemplate执行调用前,设置异常处理类
restTemplate.setErrorHandler(new CustomResponseErrorHandler());
public class CustomResponseErrorHandler implements ResponseErrorHandler {
private ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler();
@Override
public void handleError(ClientHttpResponse response) throws IOException {
List<String> customHeader = response.getHeaders().get("x-app-err-id");
String svcErrorMessageID = "";
if (customHeader != null) {
svcErrorMessageID = customHeader.get(0);
}
String body = convertStreamToString(response.getBody());
try {
errorHandler.handleError(response);
} catch (RestClientException scx) {
throw new CustomException(scx.getMessage(), scx, body);
}
}
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return errorHandler.hasError(response);
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
2. 捕捉异常
try {
} catch (CustomException e) {
JSONObject info = JSONObject.parseObject(e.getBody());
JSONObject meta = JSONObject.parseObject(info.get("meta").toString());
String message = meta.get("message").toString();
e.printStackTrace();
log.error(message, e);
}
public class CustomException extends RestClientException {
private RestClientException restClientException;
private String body;
public RestClientException getRestClientException() {
return restClientException;
}
public void setRestClientException(RestClientException restClientException) {
this.restClientException = restClientException;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public CustomException(String msg, RestClientException restClientException, String body) {
super(msg);
this.restClientException = restClientException;
this.body = body;
}
}
代码网上整合而来的,具体链接忘了…
|