Skip to content

Commit

Permalink
Add a custom error middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
mattesmohr committed Jan 16, 2024
1 parent ac54514 commit b7ccc7b
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
18 changes: 18 additions & 0 deletions Sources/Website/Middlewares/ErrorMiddleware.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import Vapor

struct ErrorMiddleware: AsyncMiddleware {

public func respond(to request: Request, chainingTo next: AsyncResponder) async throws -> Response {

do {
return try await next.respond(to: request)

} catch {

request.logger.report(error: error)

return try await request.htmlkit.render(ErrorPage.ErrorView(message: error.localizedDescription))
.encodeResponse(for: request)
}
}
}
2 changes: 2 additions & 0 deletions Sources/Website/Setup.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ struct Setup {
application.passwords.use(.bcrypt)
application.sessions.use(.fluent(.mysql))

application.middleware = .init()
application.middleware.use(ErrorMiddleware())
application.middleware.use(FileMiddleware(publicDirectory: application.directory.publicDirectory))
application.middleware.use(application.sessions.middleware)

Expand Down
26 changes: 26 additions & 0 deletions Sources/Website/Views/Shared/ErrorPage.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import HTMLKit
import HTMLKitComponents

enum ErrorPage {

struct ErrorView: View {

var message: String

var body: Content {
AreaViewContainer {
Section {
VStack(spacing: .small) {
Text {
"Ooops!"
}
.textStyle(.headline)
Text {
"Something went wrong (\(message)). Sorry for the inconvenience!"
}
}
}
}
}
}
}

0 comments on commit b7ccc7b

Please sign in to comment.