Skip to content

Commit 58c5176

Browse files
committed
add error support for non-200 status codes, include body by default on PUT requests.
1 parent 6409170 commit 58c5176

File tree

5 files changed

+68
-13
lines changed

5 files changed

+68
-13
lines changed

Sources/Bifrost/API.swift

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
//
2-
// API.swift
3-
//
42
// Copyright (c) 2021 @mtzaquia
53
//
64
// Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -129,12 +127,20 @@ public extension API {
129127
Logger.bifrost.debug("Header fields: \(urlRequest.allHTTPHeaderFields ?? [:])")
130128
}
131129

132-
let task = urlSession.dataTask(with: urlRequest) { data, _, error in
130+
let task = urlSession.dataTask(with: urlRequest) { data, response, error in
133131
if let error = error {
134132
callback(.failure(error))
135133
return
136134
}
137-
135+
136+
if let statusCode = (response as? HTTPURLResponse)?.statusCode,
137+
!(200..<300).contains(statusCode),
138+
let error = request.error(for: statusCode)
139+
{
140+
callback(.failure(error))
141+
return
142+
}
143+
138144
guard let data = data else {
139145
callback(.failure(URLError(.cannotDecodeRawData)))
140146
return

Sources/Bifrost/BifrostError.swift

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//
2+
// Copyright (c) 2024 @mtzaquia
3+
//
4+
// Permission is hereby granted, free of charge, to any person obtaining a copy
5+
// of this software and associated documentation files (the "Software"), to deal
6+
// in the Software without restriction, including without limitation the rights
7+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8+
// copies of the Software, and to permit persons to whom the Software is
9+
// furnished to do so, subject to the following conditions:
10+
//
11+
// The above copyright notice and this permission notice shall be included in all
12+
// copies or substantial portions of the Software.
13+
//
14+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20+
// SOFTWARE.
21+
//
22+
23+
import Foundation
24+
25+
/// A custom type for generic errors with status code or wrapping underlying errors.
26+
public enum BifrostError: LocalizedError {
27+
/// A request returned a response with a non-success (200-299) status code.
28+
case unsuccessfulStatusCode(_: Int)
29+
/// A request returned an error that has an underlying error.
30+
case wrapping(Error)
31+
32+
public var errorDescription: String? {
33+
switch self {
34+
case .unsuccessfulStatusCode(let statusCode):
35+
return "\(statusCode): An error ocurred."
36+
case .wrapping(let error):
37+
return error.localizedDescription
38+
}
39+
}
40+
}

Sources/Bifrost/Requestable.swift

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
//
2-
// Requestable.swift
3-
//
42
// Copyright (c) 2021 @mtzaquia
53
//
64
// Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -68,6 +66,15 @@ public protocol Requestable: Encodable {
6866
/// - Parameter encoder: The JSON encoder that should be used for building the result.
6967
/// - Returns: The HTTP body to be embeded with the request.
7068
func bodyParameters(_ encoder: JSONEncoder) throws -> Data?
69+
70+
/// A function providing a custom error for a given status code.
71+
///
72+
/// By default, ``BifrostError/unsuccessfulStatusCode(_:message:)`` is
73+
/// returned when a response's status code is not within the 200-299 range.
74+
///
75+
/// - Parameter statusCode: The status code from the response.
76+
/// - Returns: The error to be thrown by the request.
77+
func error(for statusCode: Int) -> BifrostError?
7178
}
7279

7380
public extension Requestable {
@@ -83,10 +90,14 @@ public extension Requestable {
8390
}
8491

8592
func bodyParameters(_ encoder: JSONEncoder) throws -> Data? {
86-
if method == .post {
93+
if [HTTPMethod.post, .put].contains(method) {
8794
return try encoder.encode(self)
8895
} else {
8996
return nil
9097
}
9198
}
99+
100+
func error(for statusCode: Int) -> BifrostError? {
101+
BifrostError.unsuccessfulStatusCode(statusCode)
102+
}
92103
}

Sources/Bifrost/Utils/DictionaryEncoder.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
//
2-
// DictionaryEncoder.swift
3-
//
42
// Copyright (c) 2021 @mtzaquia
53
//
64
// Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -49,7 +47,9 @@ public class DictionaryEncoder {
4947
}
5048

5149
func encode<T>(_ value: T) throws -> [String: Any] where T: Encodable {
52-
try JSONSerialization.jsonObject(with: try encoder.encode(value),
53-
options: .allowFragments) as! [String: Any]
50+
try JSONSerialization.jsonObject(
51+
with: try encoder.encode(value),
52+
options: .allowFragments
53+
) as! [String: Any]
5454
}
5555
}

Sources/Bifrost/Utils/Logging.swift

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
//
2-
// Logging.swift
3-
//
42
// Copyright (c) 2021 @mtzaquia
53
//
64
// Permission is hereby granted, free of charge, to any person obtaining a copy

0 commit comments

Comments
 (0)