PXshadow / weblink

MIT License
41 stars 7 forks source link

Add middleware for catching exceptions #38

Closed Frixuu closed 1 month ago

Frixuu commented 1 month ago

Currently, throwing exceptions inside HTTP handlers (.get() etc.) crashes the server.

This PR introduces OPTIONAL, included middleware that translates thrown exceptions into proper HTTP responses. Additionally, weblink.HTTPException was superseded by one with an explicit status code field.

Example usage:

import weblink.Weblink;
import weblink.exceptions.HttpException;
import weblink.middleware.DefaultMiddleware;

function main() {
    final app = new Weblink();
    app.use(DefaultMiddleware.recoverFromExceptions());
    app.get("/", (_, _) -> throw new HttpException(ImATeapot, "Hello World!"));
    app.listen(2000, true);
}
➜ curl -i http://localhost:2000/

HTTP/1.1 418 I'm a teapot
Connection: keep-alive
Content-type: text/plain
Content-length: 12

I'm a teapot%

Additionally, non-production deployments can be configured to include stack traces in the responses:

-   app.use(DefaultMiddleware.recoverFromExceptions());
+   app.use(DefaultMiddleware.recoverFromExceptions(options -> {
+       options.includeStackTrace = true;
+   }));
➜ curl -i http://localhost:2000/

HTTP/1.1 418 I'm a teapot
Connection: keep-alive
Content-type: text/plain
Content-length: 715

I'm a teapot

Exception: Hello World!
Called from _Example.$Example_Fields_.~main.1 (Example.hx line 10)
Called from local function #693 (weblink/middleware/DefaultMiddleware.hx line 34)
Called from weblink._internal.Server.complete (weblink/_internal/Server.hx line 87)
Called from local function #675 (weblink/_internal/Server.hx line 38)
Called from hl.uv.Stream.~readStart.0 (/usr/share/haxe/std/hl/uv/Stream.hx line 42)
Called from haxe.$MainLoop.tick (/usr/share/haxe/std/haxe/MainLoop.hx line 179)
Called from weblink._internal.Server.update (weblink/_internal/Server.hx line 101)
Called from weblink.Weblink.listen (weblink/Weblink.hx line 89)
Called from _Example.$Example_Fields_.main (Example.hx line 11)%