Serve up custom 404 and server error pages for your Vapor App
Switch branches/tags
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
Sources/LeafErrorMiddleware
Tests
.codecov.yml
.gitignore
.travis.yml
CODE_OF_CONDUCT.md
CONTRIBUTING.md
LICENSE
Package.swift
README.md

README.md

Leaf Error Middleware

Language Build Status Code Coverage MIT License

Leaf Error Middleware is a piece of middleware for Vapor which allows you to return custom 404 and server error pages.

Note that this middleware is designed to be used for Leaf front-end websites only - it should not be used for providing JSON error responses for an API, for example.

Usage

First, add LeafErrorMiddleware as a dependency in your Package.swift file:

dependencies: [
    // ...,
    .package(url: "https://github.com/brokenhandsio/leaf-error-middleware.git", from: "1.0.0")
],
targets: [
    .target(name: "App", dependencies: ["Vapor", ..., "LeafErrorMiddleware"]),
    // ...
]

To use the LeafErrorMiddleware, register the middleware service in configure.swift (make sure you import LeafErrorMiddleware at the top):

// You must set the preferred renderer:
config.prefer(LeafRenderer.self, for: TemplateRenderer.self)

services.register { worker in
    return try LeafErrorMiddleware(environment: worker.environment)
}

Then add it to your MiddlewareConfig:

var middlewares = MiddlewareConfig()
middlewares.use(LeafErrorMiddleware.self)
// ...
services.register(middlewares)

This replaces the default error middleware in Vapor, so do not add the default ErrorMiddleware to your MiddlewareConfig.

Setting Up

You need to include two Leaf templates in your application:

  • 404.leaf
  • serverError.leaf

When Leaf Error Middleware catches a 404 error, it will return the 404.leaf template. Any other error caught will return the serverError.leaf template. The serverError.leaf template will be passed two parameters:

  • status - the status code of the error caught
  • statusMessage - a reason for the status code