API接口交互异常捕获通用处理逻辑

发布时间:2026/9/15 17:44:53
API接口交互异常捕获通用处理逻辑 HttpClientErrorException客户端请求异常4xx等状态码如接口交互式使用了tokentoken过期了等场景。需从客户端进行排查。HttpServerErrorException服务器内部异常5xx等状态码。需从服务端进行排查。ResourceAccessException网络异常读超时或连接超时资源不可访问等RestClientExceptionspring中restTemplate请求异常是HttpClientErrorException、ResourceAccessException、HttpServerErrorException的父类Exception兜底异常try { //业务逻辑使用RestTemplate请求时绝大多数异常都是RestClientException的子类 //其他异常使用Exception兜底 } catch (HttpClientErrorException hcee) { //客户端请求异常4xx等状态码如接口交互式使用了tokentoken过期了等场景。 //需从客户端进行排查。 } catch (HttpServerErrorException hsee) { //服务器内部异常5xx等状态码。需从服务端进行排查。 } catch (ResourceAccessException ex) { //网络异常读超时或连接超时资源不可访问等 } catch (RestClientException rse) { //RestClientException是ResourceAccessException、HttpServerErrorException、 //HttpClientErrorException的父类捕获RestTemplate请求时其他暂未遇到的场景的异常 } catch (Exception e) { //其他异常兜底 ​​​​​​​ }