Giter VIP home page Giter VIP logo

leaf-error-middleware's Introduction

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: "4.0.0")
],
targets: [
    .target(
        name: "App", 
        dependencies: [
            .product(name: "Vapor", package: "vapor"),
            ..., 
            .product(name: "LeafErrorMiddleware", package: "leaf-error-middleware")
        ]
    ),
    // ...
]

Default Context

To use the LeafErrorMiddleware with the default context passed to templates, register the middleware service in configure.swift to your Application's middleware (make sure you import LeafErrorMiddleware at the top):

app.middleware.use(LeafErrorMiddlewareDefaultGenerator.build())

Make sure it appears before all other middleware to catch errors.

Custom Context

Leaf Error Middleware allows you to pass a closure to LeafErrorMiddleware to generate a custom context for the error middleware. This is useful if you want to be able to tell if a user is logged in on a 404 page for instance.

Register the middleware as follows:

let leafMiddleware = LeafErrorMiddleware() { status, error, req async throws -> SomeContext in
    SomeContext()
}
app.middleware.use(leafMiddleware)

The closure receives three parameters:

  • HTTPStatus - the status code of the response returned.
  • Error - the error caught to be handled.
  • Request - the request currently being handled. This can be used to log information, make external API calls or check the session.

Custom Mappings

By default, you need to include two Leaf templates in your application:

  • 404.leaf
  • serverError.leaf

However, you may elect to provide a dictionary mapping arbitrary error responses (i.e >= 400) to custom template names, like so:

let mappings: [HTTPStatus: String] = [
    .notFound: "404",
    .unauthorized: "401",
    .forbidden: "403"
]
let leafMiddleware = LeafErrorMiddleware(errorMappings: mappings) { status, error, req async throws -> SomeContext in
    SomeContext()
}

app.middleware.use(leafMiddleware)
// OR
app.middleware.use(LeafErrorMiddlewareDefaultGenerator.build(errorMappings: mapping))

By default, when Leaf Error Middleware catches a 404 error, it will return the 404.leaf template. This particular mapping also allows returning a 401.leaf or 403.leaf template based on the error. Any other error caught will return the serverError.leaf template. By providing a mapping, you override the default 404 template and will need to respecify it if you want to use it.

Default Context

If using the default context, the serverError.leaf template will be passed up to three parameters in its context:

  • status - the status code of the error caught
  • statusMessage - a reason for the status code
  • reason - the reason for the error, if known. Otherwise this won't be passed in.

The 404.leaf template and any other custom error templates will get a reason parameter in the context if one is known.

leaf-error-middleware's People

Contributors

0xtim avatar bre7 avatar dannflor avatar gaetandezeiraud avatar ptoffy avatar tonyarnold avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

leaf-error-middleware's Issues

Allow throw Abort.redirect()

Currently when doing throw Abort.redirect("/some-route") is being redirected to serverError.leaf, many of 3xx codes are not really errors.
This middleware should allow redirect errors to pass through, since sometimes it's just easier to abort.
Since all authentication redirect functionality has been removed from vapor (can't find it in vapor 3, but google shows it was there), imagine a helper function:

	@discardableResult
	func checkAuth(_ req: Request) throws -> User {
		do {
			return try req.requireAuthenticated(User.self)
		}
		catch {
			throw Abort.redirect(to: "/login")
		}
	}

If it fails, serverError.leaf will be shown with 303 error instead of redirect.

How to use with a specific route?

I'd like to host both API and public web endpoints in a single app, but I don't want HTML error pages for my API endpoints.

I've tried the following, without registering against the default middlewares:

router.grouped(LeafErrorMiddleware.self)

But it doesn't work.

Custom 404 reason(s) passed

I'm just wondering if it's possible to pass through a custom 404 error reason (say, "this article ID is not valid") instead of just a blank 404 error with no reason for it?

I feel this could be an enhancement since the boilerplate already exists for server errors.

Typo in LeafErorrMiddlewareDefaultGenerator

LeafErorrMiddlewareDefaultGenerator should be LeafErrorMiddlewareDefaultGenerator - it’s a minor type in spelling of “error” but trips up in the setup. The configuration will not work otherwise. Can this be fixed. Thanks.

got 'leaf-error-middleware' exists and is not an empty directory (-4)

In Package.swift:

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

but got

Showing Recent Messages
An unknown error occurred. '/Users/.../SourcePackages/checkouts/leaf-error-middleware' exists and is not an empty directory (-4)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.