HTMX error handling.

This commit is contained in:
mikestefanello 2021-12-23 20:58:49 -05:00
parent 8860b981e6
commit 576caf217c
6 changed files with 24 additions and 16 deletions

View File

@ -156,6 +156,11 @@ func (c *Controller) Redirect(ctx echo.Context, route string, routeParams ...int
return ctx.Redirect(http.StatusFound, ctx.Echo().Reverse(route, routeParams))
}
func (c *Controller) Fail(ctx echo.Context, err error, log string) error {
ctx.Logger().Errorf("%s: %v", log, err)
return echo.NewHTTPError(500)
}
// SetValidationErrorMessages sets error flash messages for validation failures of a given struct
// and attempts to provide more user-friendly wording.
// The error should result from the validator module and the data should be the struct that failed

View File

@ -34,29 +34,21 @@ func (c *Contact) Get(ctx echo.Context) error {
}
func (c *Contact) Post(ctx echo.Context) error {
//fail := func(message string, err error) error {
// ctx.Logger().Errorf("%s: %v", message, err)
// msg.Danger(ctx, "An error occurred. Please try again.")
// return c.Get(ctx)
//}
// TODO: Error handling w/ HTMX support
// Parse the form values
var form ContactForm
if err := ctx.Bind(&form); err != nil {
ctx.Logger().Error(err)
return c.Fail(ctx, err, "unable to bind form")
}
if err := form.Submission.Process(ctx, form); err != nil {
// TOOD
return c.Fail(ctx, err, "unable to process form submission")
}
ctx.Set(context.FormKey, form)
if !form.Submission.HasErrors() {
if err := c.Container.Mail.Send(ctx, form.Email, "Hello!"); err != nil {
ctx.Logger().Error(err)
return c.Fail(ctx, err, "unable to send email")
}
}

View File

@ -33,6 +33,7 @@ func (e *Error) Get(err error, c echo.Context) {
p.Title = http.StatusText(code)
p.Name = "error"
p.StatusCode = code
p.HTMX.Request.Enabled = false
if err = e.RenderPage(c, p); err != nil {
c.Logger().Error(err)

View File

@ -24,9 +24,19 @@
{{define "footer"}}
{{- if .CSRF}}
<script>
document.body.addEventListener('htmx:configRequest', (event) => {
event.detail.parameters['csrf'] = '{{ .CSRF }}';
document.body.addEventListener('htmx:configRequest', function(evt) {
if (evt.detail.verb !== "get") {
evt.detail.parameters['csrf'] = '{{ .CSRF }}';
}
})
</script>
{{end}}
<script>
document.body.addEventListener('htmx:beforeSwap', function(evt) {
if (evt.detail.xhr.status >= 400){
evt.detail.shouldSwap = true;
evt.detail.target = htmx.find("body");
}
});
</script>
{{end}}

View File

@ -39,6 +39,6 @@
</div>
</section>
{{template "footer"}}
{{template "footer" .}}
</body>
</html>

View File

@ -1,6 +1,6 @@
{{define "content"}}
{{if gt .StatusCode 500}}
<p>Please try again. Request ID: {{.RequestID}}</p>
{{if ge .StatusCode 500}}
<p>Please try again.</p>
{{else if or (eq .StatusCode 403) (eq .StatusCode 401)}}
<p>You are not authorized to view the requested page.</p>
{{else if eq .StatusCode 404}}