RxAlamofire调用出错时如何获取响应内容?
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

