在Java中实现API调用时,有效的错误处理和异常管理是确保应用程序稳定性和可靠性的关键。以下是一些关键步骤和最佳实践:
1. 异常捕获
使用try-catch
块来捕获和处理可能发生的异常。
try {
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
// 处理响应数据
} else {
// 处理非200响应
throw new RuntimeException("Unexpected response status: " + response.statusCode());
}
} catch (InterruptedException e) {
// 处理中断异常
Thread.currentThread().interrupt();
} catch (IOException e) {
// 处理IO异常
throw new UncheckedIOException("Network I/O error", e);
}
2. 检查响应状态
检查HTTP响应状态码,并根据状态码处理不同的响应。
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 400) {
throw new ApiException("Error from server: " + response.body());
}
3. 自定义异常
创建自定义异常类,以便更精确地表示不同的错误情况。
public class ApiException extends Exception {
public ApiException(String message) {
super(message);
}
public ApiException(String message, Throwable cause) {
super(message, cause);
}
}
4. 超时和重试机制
为网络请求设置超时,并在发生超时或临时故障时实现重试逻辑。
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.timeout(Duration.ofSeconds(10))
.GET()
.build();
// 使用重试机制发送请求
sendRequestWithRetry(request, 3); // 最多重试3次
5. 日志记录
记录详细的错误日志,这对于调试和监控应用程序非常有用。
import java.util.logging.Logger;
private static final Logger LOGGER = Logger.getLogger("ApiClient");
catch (Exception e) {
LOGGER.log(Level.SEVERE, "API调用失败", e);
throw e;
}
6. 资源清理
确保在捕获异常后正确释放资源,如关闭连接和流。
try (CloseableHttpResponse response = httpClient.execute(request)) {
// 处理响应
} catch (IOException e) {
// 处理异常
}
7. 错误传播
在无法处理异常时,通过抛出异常来让调用者知道错误。
catch (IOException e) {
throw new ApiException("Network error", e);
}
8. 使用断路器模式
实现断路器模式,防止系统在故障时继续执行可能导致错误的操作。
if (circuitBreaker.isOpen()) {
throw new RuntimeException("Service is currently unavailable");
} else {
try {
// 执行API调用
} catch (Exception e) {
circuitBreaker.open();
throw e;
}
}
9. 单元测试
编写单元测试来验证错误处理逻辑是否按预期工作。
@Test(expected = ApiException.class)
public void testApiCallFailure() throws Exception {
// 模拟API调用失败
when(mockHttpClient.execute(any(HttpGet.class))).thenThrow(new IOException("Network error"));
service.getUserInfo("user123");
}
10. 用户友好的错误信息
向最终用户提供清晰和友好的错误信息。
catch (ApiException e) {
return "服务暂时不可用,请稍后再试。";
}