Skip to content

Commit ac44daa

Browse files
committed
Created ModelNotFound ErrorCatchingSpecialization implementation
1 parent 95427cd commit ac44daa

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

Sources/APIErrorMiddleware/APIErrorMiddleware.swift

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,6 @@ public final class APIErrorMiddleware: Middleware, Service, ServiceType {
1313
/// to `ErrorResult` objects.
1414
let specializations: [ErrorCatchingSpecialization]
1515

16-
// We define an empty init because the one
17-
// synthesized bby Swift is marked `internal`.
18-
1916
/// Create an instance if `APIErrorMiddleware`.
2017
public init(specializations: [ErrorCatchingSpecialization] = []) {
2118
self.specializations = specializations

Sources/APIErrorMiddleware/Specialization/Specialization.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,19 @@ public protocol ErrorCatchingSpecialization {
3737
/// passed in.
3838
func convert(error: Error, on request: Request) -> ErrorResult?
3939
}
40+
41+
// MARK: - ErrorCatchingSpecialization implementations
42+
43+
/// Catches Fluent's `modelNotFound` error and returns a 404 status code.
44+
public struct ModelNotFound: ErrorCatchingSpecialization {
45+
public func convert(error: Error, on request: Request) -> ErrorResult? {
46+
if let error = error as? Debuggable, error.identifier == "modelNotFound" {
47+
48+
// We have the infamous `modelNotFound` error from Fluent that returns
49+
// a 500 status code instead of a 404.
50+
// Set the message to the error's `reason` and the status to 404 (Not Found)
51+
return ErrorResult(message: error.reason, status: .notFound)
52+
}
53+
return nil
54+
}
55+
}

0 commit comments

Comments
 (0)