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

RxAlamofire调用出错时如何获取响应内容?

How to Retrieve the Response Body When RxAlamofire Calls Fail

I totally get the frustration—out-of-the-box RxAlamofire doesn’t make it straightforward to access the response body when an error occurs. Hacky workarounds can feel clunky, so creating a custom fork of RxAlamofire that surfaces this data directly is a clean, intentional solution.

With your modified fork, errors thrown by RxAlamofire will be instances of DataResponseError<Data>, which lets you access the full underlying response (including its body data) right in the onError handler. Here’s how to implement this:

RxAlamofire.data(method, url)
    .subscribe(
        onNext: { data in
            // Handle successful response data here
        },
        onError: { error in
            if let dataResponseError = error as? DataResponseError<Data> {
                // Retrieve the response body data
                if let responseData = dataResponseError.response.data {
                    // Convert data to a readable string (adjust encoding as needed)
                    if let responseString = String(data: responseData, encoding: .utf8) {
                        print("Error response body: \(responseString)")
                    }
                }
                // You can also access other response details like status code
                let statusCode = dataResponseError.response.statusCode
                print("Error status code: \(statusCode)")
            }
        }
    )
    .disposed(by: disposeBag)

This approach eliminates messy workarounds by encapsulating the full response context within the error type itself, making error handling more concise and maintainable.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:20:40