Java 自定义异常中外部服务调用异常怎么定义
在 java 中定义外部服务调用异常,核心做法是创建一个继承自 runtimeexception 的类,并在构造函数中保留原始异常以便追踪。通常建议将此类命名为 externalserviceexception,通过它包装 httpclient 或 resttemplate 抛出的底层错误,从而在业务层统一处理网络超时、连接拒绝或服务不可用等状况。

如何封装 HTTP 客户端调用的具体实现
封装的具体实现依赖于使用 try-catch 块捕获具体的 IO 或网络异常,并将其转换为自定义异常抛出。开发者需要确保在构造异常时传入 HTTP 状态码或错误信息,这样调用方可以通过 getCause() 获取详细的失败原因,而不丢失上下文信息。

掌握 ES6+ 特性,包括 async/await、解构、扩展运算符、箭头函数、Promise、模块、迭代器、生成器以及函数式编程模式,编写简洁高效的 Java
import java.io.IOException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ServiceClient {
private final HttpClient client = HttpClient.newHttpClient();
public String callExternalService(String url) {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(java.net.URI.create(url))
.GET()
.build();
HttpResponse<string> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new ExternalServiceException("HTTP Error: " + response.statusCode(), null);
}
return response.body();
} catch (IOException | InterruptedException e) {
throw new ExternalServiceException("Failed to connect to external service", e);
}
}
}</string>
如何处理外部服务返回的非 2xx 状态码
当外部服务返回非 2xx 状态码时,程序应显式抛出带有状态码信息的 ExternalServiceException。这允许上层逻辑根据具体的错误代码(如 404 或 503)执行不同的重试或降级策略,而不是仅仅将其视为通用的网络故障。

import java.io.IOException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ServiceClient {
private final HttpClient client = HttpClient.newHttpClient();
public String callExternalService(String url) {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(java.net.URI.create(url))
.GET()
.build();
HttpResponse<string> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
if (status == 404) {
throw new ExternalServiceException("Resource not found", null);
} else if (status >= 500) {
throw new ExternalServiceException("Server error on remote host", null);
}
return response.body();
} catch (IOException | InterruptedException e) {
throw new ExternalServiceException("Network failure", e);
}
}
}</string>
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










