'Parse JSON when I get a error response in Alamofire

I've been working on API requests using Alamofire, and I want to know something for parsing the Error and to get the JSON data from the server instead of accessing the AFErrors. The code below works fine, but since I've been using .responseDecodable for decoding the response and also the MyError inherits Decodable, I was wondering if there is a similar way to decode data when I get the error response back, instead of using JSONDecoder().decode. When I get the error response, it returns a JSON object with one value in it (message) from the server.

static let sessionManager: Session  = {
    let configuration = URLSessionConfiguration.af.default
    configuration.timeoutIntervalForRequest = 30
    return Session(configuration: configuration)
}()

Request.sessionManager.request(endpoint, method: httpMethod, parameters: params, headers: headers)
        .responseDecodable(of: resDecodeType.self) { response in
            switch response.result {
            case .success(let successResponse):
                completed(.success(successResponse))
            case .failure(let error):
                let errorStatusCode = response.response?.statusCode
                do {
                    let data = try JSONDecoder().decode(MyError.self, from: response.data!) // -> this part...
                } catch {
                    print(error)
                }

            }
        }
}

struct MyError: Decodable {
    let message: String
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source