Repository navigation
|
Hi guys, I was wondering what would be the best approach for using the centralized error handling approach when working with a server that both serves HTML and JSON over HTTP. My stack is Go+Templ+Echo. The custom error handler works fine on the JSON part as I can do stuff like: I just catch all the errors after the handlers, either there are no errors and I do nothing, or there is an error, I store it and send a response. When using Templ, i do: I don't really care about the error from the render function. For now if there is a business error, since the render function rarely throws any error, I never log anything. How should i manage this? |
Replies: 1 comment
|
The business error is lost at this line: return render(c, templates.Index("some stuff"))If rendering succeeds, that returns A useful arrangement is to mark your HTML routes with a context value such as
Buffer the templ output before committing the response, so a rendering failure does not send partial HTML with a successful status: func renderHTML(c echo.Context, status int, component templ.Component) error {
var buf bytes.Buffer
if err := component.Render(c.Request().Context(), &buf); err != nil {
return err
}
return c.HTMLBlob(status, buf.Bytes())
}This uses There are also two issues in the handler you posted:
I checked the error flow with Echo v4.15.4 and templ v0.3.1020: returned errors reached the centralized handler for both response formats, and a failed buffered render left the response uncommitted. References: Echo error handling and templ components. |
The business error is lost at this line:
If rendering succeeds, that returns
nil, so Echo has no error to pass to your centralized handler. Return the business error from the route and let the centralized handler log it and choose the HTML or JSON response.A useful arrangement is to mark your HTML routes with a context value such as
c.Set("responseFormat", "html"). In the error handler:c.Response().Committedis true, stop: the response can no longer be replaced.c.JSON.Bu…