Skip to content

Commit

Permalink
Improve error mapping
Browse files Browse the repository at this point in the history
  • Loading branch information
Sherlouk committed Aug 13, 2021
1 parent db3d218 commit b413121
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,5 @@ In order to use this package, you will first need to obtain an API key from [Sto
- [x] Inline Documentation
- [ ] README Documentation
- [x] Access Control Audit
- [ ] Error Handling
- [ ] Swift 5 Async Support (?)
- [x] Error Handling
- [x] Add to SPI
20 changes: 19 additions & 1 deletion Sources/StormGlass/Networking/SGNetworking.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ public struct SGRequest<Endpoint: SGEndpoint> {

public func fetch(completion: @escaping (Result<Endpoint.Response, Error>) -> Void) {
do {
let task = try urlSession.dataTask(with: makeRequest()) { data, _, error in
let task = try urlSession.dataTask(with: makeRequest()) { data, response, error in
// Network Errors

if let error = error {
completion(.failure(error))
return
Expand All @@ -75,6 +77,22 @@ public struct SGRequest<Endpoint: SGEndpoint> {
return
}

// Error Handling

if let error = try? self.decoder.decode(SGErrorResponse.self, from: data) {
completion(.failure(error))
return
}

if let httpResponse = response as? HTTPURLResponse,
let error = SGServiceError(statusCode: httpResponse.statusCode)
{
completion(.failure(error))
return
}

// Decode Response

do {
let result = try self.decoder.decode(Endpoint.Response.self, from: data)
completion(.success(result))
Expand Down
17 changes: 16 additions & 1 deletion Sources/StormGlass/SGServiceError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public enum SGServiceError: LocalizedError {

internal init?(statusCode: Int) {
switch statusCode {
case 400:
case 400, 422:
self = .badRequest
case 401:
self = .unauthorised
Expand Down Expand Up @@ -71,3 +71,18 @@ public enum SGServiceError: LocalizedError {
}
}
}

public struct SGErrorResponse: Error, Decodable, CustomStringConvertible {
public struct Item: Decodable {
let key: String?
let params: [String]?
}

public let errors: Item

public var description: String {
errors.key ??
errors.params?.joined(separator: "\n\n") ??
"Unknown Error"
}
}

0 comments on commit b413121

Please sign in to comment.