Skip to content

Commit

Permalink
Merge branch 'master' of github.com:asensei/vapor-fluent-mongo
Browse files Browse the repository at this point in the history
* 'master' of github.com:asensei/vapor-fluent-mongo:
  added custom connection errors (#4)
  • Loading branch information
valeriomazzeo committed Jan 29, 2019
2 parents a9a1cdd + 5247f06 commit 3c71d2a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
23 changes: 22 additions & 1 deletion Sources/FluentMongo/MongoConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,16 @@ public final class MongoConnection: BasicWorker, DatabaseConnection, DatabaseQue
}

return self.worker.future()
} catch let error as MongoError {
switch error {
// TODO: update this as soon as https://github.com/mongodb/mongo-swift-driver/issues/200 is fixed.
case .commandError(let message) where message.hasPrefix("E11000"):
return self.worker.future(error: Error.duplicatedKey(message))
default:
return self.worker.future(error: Error.underlyingDriverError(error))
}
} catch {
return self.worker.future(error: error)
return self.worker.future(error: Error.underlyingDriverError(error))
}
}

Expand Down Expand Up @@ -195,5 +203,18 @@ extension MongoConnection {
public extension MongoConnection {
public enum Error: Swift.Error {
case invalidQuery(Database.Query)
case duplicatedKey(String)
case underlyingDriverError(Swift.Error)

var localizedDescription: String {
switch self {
case .invalidQuery(let query):
return "Invalid query. \(String(describing: query))"
case .duplicatedKey(let message):
return "Duplicated key. \(message)"
case .underlyingDriverError(let error):
return error.localizedDescription
}
}
}
}
18 changes: 18 additions & 0 deletions Tests/FluentMongoTests/FluentMongoProviderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,24 @@ class FluentMongoProviderTests: XCTestCase {
}
}

func testError() throws {
let conn = try self.database.newConnection(on: MultiThreadedEventLoopGroup(numberOfThreads: 1)).wait()

let uuid = UUID()
XCTAssertNoThrow(try User(_id: uuid, name: "asdf", age: 42).create(on: conn).wait())

XCTAssertThrowsError(try User(_id: uuid, name: "asdf", age: 42).create(on: conn).wait(), "duplicatedKey") { error in
guard
let connectionError = error as? MongoConnection.Error,
case .duplicatedKey = connectionError
else {
XCTFail("\(error) is not equal to MongoConnection.Error.duplicatedKey")

return
}
}
}

func testFilterCollectionInSubset() {
do {
let conn = try self.database.newConnection(on: MultiThreadedEventLoopGroup(numberOfThreads: 1)).wait()
Expand Down

0 comments on commit 3c71d2a

Please sign in to comment.