1. restTemplate执行调用前,设置异常处理类
//1.执行调用前,设置异常处理类
restTemplate.setErrorHandler(newCustomResponseErrorHandler());
publicclassCustomResponseErrorHandlerimplementsResponseErrorHandler{private ResponseErrorHandler errorHandler=newDefaultResponseErrorHandler();@OverridepublicvoidhandleError(ClientHttpResponse response)throws IOException{// 对请求头的处理
List<String> customHeader= response.getHeaders().get("x-app-err-id");
String svcErrorMessageID="";if(customHeader!= null){
svcErrorMessageID= customHeader.get(0);}//对body 的处理 (inputStream)
String body=convertStreamToString(response.getBody());try{
errorHandler.handleError(response);}catch(RestClientException scx){thrownewCustomException(scx.getMessage(), scx, body);}}@OverridepublicbooleanhasError(ClientHttpResponse response)throws IOException{return errorHandler.hasError(response);}/**
* inputStream 装换为 string
*/private StringconvertStreamToString(InputStream is){
BufferedReader reader=newBufferedReader(newInputStreamReader(is));
StringBuilder sb=newStringBuilder();
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);}
publicclassCustomExceptionextendsRestClientException{private RestClientException restClientException;private String body;public RestClientExceptiongetRestClientException(){return restClientException;}publicvoidsetRestClientException(RestClientException restClientException){this.restClientException= restClientException;}public StringgetBody(){return body;}publicvoidsetBody(String body){this.body= body;}publicCustomException(String msg, RestClientException restClientException, String body){super(msg);this.restClientException= restClientException;this.body= body;}}
代码网上整合而来的,具体链接忘了…