Moya / Moya

Network abstraction layer written in Swift.
https://moya.github.io
MIT License
15.15k stars 1.99k forks source link

Suggestion: add helper methods to MoyaError to get response from server #1415

Open jgongo opened 7 years ago

jgongo commented 7 years ago

I've been recently faced with getting the error information from the server when filtering successful response codes. As I explain in this StackOverflow response, I think the easiest and cleanest way is to extend MoyaError to provide access to the body response, using code like this:

struct BackendError: Decodable { ... }

extension MoyaError {
    public var backendError: BackendError? {
        return response.flatMap {
            try? $0.map(BackendError.self)
        }
    }
}

so you can later retrieve the information in this way:

onError: { error in
    let backendError = (error as? MoyaError).backendError
}

When doing this I thought it may be interesting to include generic methods in the Moya framework itself, so users of the framework don't have to manually invoke mapping methods on the response included in the MoyaError. What do you think?

AndrewSB commented 7 years ago

It sounds interesting, but it's hard to say without more concrete thoughts. What kind of generic methods?

jgongo commented 7 years ago

The idea would be to substitute BackendError with a generic inheriting from Decodable, so you can invoke that property/method passing the type of the error response and get the error returned by the server. It would be similar to the map method, where you pass the Decodable type to use when decoding the success response as a parameter.