You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建自定义空okhttp3.Response实例以替换请求失败时的null值?

How to Create a Non-Null Response Instance for Failed OkHttp Requests

Got it, let's solve this problem where you need to replace a null Response with a proper instance when an OkHttp request throws an IOException.

OkHttp's Response class uses the builder pattern, so you can construct a custom error response directly in your catch block to avoid returning null. Here's how to do it step by step:

Basic Implementation in Catch Block

Instead of leaving response as null, build a dedicated error response with meaningful status code, message, and error details:

Request request;
Response response = null;
try {
    response = client.newCall(request).execute();
} catch (IOException e) {
    // Build an error response to replace null
    response = new Response.Builder()
            .request(request) // Mandatory: link the response to the original request
            .protocol(Protocol.HTTP_1_1) // Required protocol version
            .code(500) // Custom HTTP status code (e.g., 500 for server/network errors)
            .message("Request failed: " + e.getMessage())
            .body(ResponseBody.create(
                    "IO Error Details: " + e.toString(),
                    MediaType.parse("text/plain; charset=utf-8")
            ))
            .build();
}

Key Notes About the Builder:

  • Mandatory: .request(request) — OkHttp requires every Response to be linked to the original Request.
  • Required: .protocol() — Specify a protocol (e.g., HTTP_1_1) to avoid build failures.
  • .code(): Choose an HTTP status code that matches the error scenario:
    • 503 for temporary network unavailability
    • 408 for request timeouts
    • 500 for generic IO/server errors
  • .body(): Include a response body to pass detailed error context (like exception details) to upstream handlers. You can pass null if no body is needed, but context is usually helpful.

Reusable Utility Method

To keep your code clean, wrap the error response creation in a utility method:

private Response createErrorResponse(Request request, Exception e) {
    return new Response.Builder()
            .request(request)
            .protocol(Protocol.HTTP_1_1)
            .code(503)
            .message("Network request failed")
            .body(ResponseBody.create(
                    "Error: " + e.getMessage() + "\nStack Trace: " + Arrays.toString(e.getStackTrace()),
                    MediaType.parse("text/plain")
            ))
            .build();
}

Then use it in your catch block:

catch (IOException e) {
    response = createErrorResponse(request, e);
}

This approach ensures you never return null from your method, eliminating null pointer exceptions and letting your upstream code handle success and error responses uniformly.

内容的提问来源于stack exchange,提问作者Zon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:39:23