Skip to content

Commit 8acac22

Browse files
committed
Wrap PostgreSQL errors
1 parent 71258f2 commit 8acac22

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

Sources/PostgresConnectionPool/PoolError.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
//
44

55
import Foundation
6+
import PostgresNIO
67

78
/// Possible errors from the connection pool.
89
public enum PoolError: Error {
@@ -13,6 +14,10 @@ public enum PoolError: Error {
1314
case connectionFailed
1415
/// The pool was already shut down.
1516
case poolDestroyed
17+
/// Some PostgreSQL error
18+
case postgresError(PSQLError)
19+
/// The query was cancelled by the server.
20+
case queryCancelled
1621
/// Something unexpected happened.
1722
case unknown
1823

Sources/PostgresConnectionPool/PostgresConnectionWrapper.swift

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,28 @@ public final class PostgresConnectionWrapper {
2121
else { throw PoolError.unknown }
2222

2323
connectionWrapper.poolConnection.query = nil
24-
let result = try await callback(connectionWrapper)
25-
connectionWrapper.poolConnection.query = nil
24+
defer {
25+
connectionWrapper.poolConnection.query = nil
26+
}
27+
28+
do {
29+
return try await callback(connectionWrapper)
30+
}
31+
catch let error as PSQLError {
32+
guard let serverInfo = error.serverInfo,
33+
let code = serverInfo[.sqlState]
34+
else { throw error }
2635

27-
return result
36+
switch PostgresError.Code(raw: code) {
37+
case .queryCanceled:
38+
throw PoolError.queryCancelled
39+
default:
40+
throw PoolError.postgresError(error)
41+
}
42+
}
43+
catch {
44+
throw error
45+
}
2846
}
2947

3048
init?(_ poolConnection: PoolConnection) {

0 commit comments

Comments
 (0)