Skip to content

Commit 4076fbe

Browse files
authored
doc(fxhttpserver): Updated documentation (ankorstore#316)
1 parent dde6802 commit 4076fbe

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

docs/modules/fxhttpserver.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,69 @@ Notes:
345345
- you can use the shortcut `*` to register a handler for all valid HTTP methods, for example `fxhttpserver.NewHandlerRegistration("*", ...)`
346346
- the valid HTTP methods are `CONNECT`, `DELETE`, `GET`, `HEAD`, `OPTIONS`, `PATCH`, `POST`, `PUT`, `TRACE`, `PROPFIND` and `REPORT`
347347

348+
### Error handler registration
349+
350+
You can use the `AsErrorHandler()` function to register a custom error handler on your HTTP server.
351+
352+
It can be any [ErrorHandler](https://github.com/ankorstore/yokai/blob/main/fxhttpserver/registry.go) implementation.
353+
354+
For example, you can create an error handler:
355+
356+
```go title="internal/errorhandler/example.go"
357+
package errorhandler
358+
359+
import (
360+
"fmt"
361+
"net/http"
362+
363+
"github.com/ankorstore/yokai/config"
364+
"github.com/ankorstore/yokai/httpserver"
365+
"github.com/ankorstore/yokai/log"
366+
"github.com/labstack/echo/v4"
367+
"go.uber.org/fx"
368+
)
369+
370+
type ExampleErrorHandler struct {
371+
config *config.Config
372+
}
373+
374+
func NewExampleErrorHandler(config *config.Config) *ExampleErrorHandler {
375+
return &ExampleErrorHandler{
376+
config: config,
377+
}
378+
}
379+
380+
func (h *ExampleErrorHandler) Handle() echo.HTTPErrorHandler {
381+
return func(err error, c echo.Context) {
382+
if c.Response().Committed {
383+
return
384+
}
385+
386+
c.String(http.StatusInternalServerError, fmt.Sprintf("error handled in example error handler of %s: %s", h.config.AppName(), err))
387+
}
388+
}
389+
```
390+
391+
You can then register your error handler:
392+
393+
```go title="internal/router.go"
394+
package internal
395+
396+
import (
397+
"github.com/ankorstore/yokai/fxhttpserver"
398+
"github.com/foo/bar/internal/errorhandler"
399+
"go.uber.org/fx"
400+
)
401+
402+
func Router() fx.Option {
403+
return fx.Options(
404+
// registers the ExampleErrorHandler as error handler
405+
fxhttpserver.AsErrorHandler(errorhandler.NewExampleErrorHandler),
406+
// ...
407+
)
408+
}
409+
```
410+
348411
## WebSocket
349412

350413
This module supports the `WebSocket` protocol, see the [Echo documentation](https://echo.labstack.com/docs/cookbook/websocket) for more information.

0 commit comments

Comments
 (0)