The ecosystem · packages/posthog
Errors in PostHog, grouped into issues, from the app itself
5xx answers, errors the app handles but wants seen, jobs that failed for good, and uncaught errors in a browser, sent to PostHog's error tracking with where they happened and who they reached.
The package is a plugin, a middleware and two route handlers, written in Roc on what any app can do (the platform has no error-reporting hook). The middleware notices failed answers, your routes take the browser's errors with the package's handlers, and a background loop sends everything to PostHog in batches, so a request never waits on PostHog.
Installing it#
Name the package in the app's header (posthog: "…/packages/posthog/main.roc"), then wire it into the program in four places:
program = App.program({
init!: |started| Ok({ started: started }),
…
plugins: [Job.plugin({ jobs: App.jobs, on_failed!: PostHog.job_failed! }), PostHog.plugin({ interval_ms: 200 })],
})import pf.Middleware
import pf.Server
import posthog.PostHog
## Who asks, from the `x-user` header ("" for nobody).
who : Middleware({ started : Str }, { started : Str, user : Str })
who = Middleware.make(|request, context, next!| next!(request, { started: context.started, user: Server.header(request, "x-user") ?? "" }))
## Every request: who asks, then every 5xx answer reported, with them.
middleware = who.then(PostHog.middleware(|context| context.user))- The middleware,
PostHog.middleware(user), goes inroutes/+middleware.roc, after the middleware that knows who is asking.usermaps that middleware's context to the person's id, or""when nobody is known. With no such middleware, put PostHog's first, with|_| "". - The plugin,
PostHog.plugin({}), goes in the app's plugins; it reads its key from the environment (where they go). - The routes for the browser's errors are yours:
routes/rocx-errors/+server.rocanswers withPostHog.errors_route!(request), androutes/rocx-errors.js/+server.rocwithPostHog.script_route(request), the page's script, which sends to its own path without.js. - Failed jobs are reported when the jobs plugin is given
on_failed!: PostHog.job_failed!.
For the browser's errors, add your route's script to the layout: <script src="/rocx-errors.js" defer></script>.
What it reports#
| What | How | Type in PostHog | Handled |
|---|---|---|---|
| an answer with a 5xx status | PostHog.middleware(user) | ServerError | no |
| an error the app dealt with | PostHog.capture!(message, fields) | Error | yes |
| a job that failed for good | on_failed!: PostHog.job_failed! | JobFailed | no |
| an error or a rejected promise nothing caught in a browser | /rocx-errors.js | the error's own (TypeError) | no |
a page that wasn't what the app renders, so the runtime rendered <body> again (a hydration mismatch) | /rocx-errors.js | HydrationMismatch | no |
A 5xx report carries the route's pattern (/posts/[id], not the path with its ids), the method, the status, the first line of the answer's text (unless it is HTML), and who asked. An error from nobody known creates no person in PostHog.
Errors wait in the server's memory (Kv, the newest 1,000). The loop sends them every ten seconds, and once more as the server stops, as $exception events to PostHog's batch endpoint.
An error the app handles#
Most of what goes wrong in a Roc app is a value, not a crash: a refusal, a database error, a fetch that timed out. To report one the app handles, call PostHog.capture!:
get! = |_input| {
PostHog.capture!("the payment provider refused a refund", { order: 42, why: "expired card" })
Ok("A person will look at your refund.")
}capture! takes a message and a record of fields, as Log.error! does. Called while answering a request, it adds that request's path and method. PostHog.capture_for!(user, message, fields) also names the person it reached, so PostHog can count the people an issue affects.
Where they go#
Give each option to PostHog.plugin({ … }), or set the first three in the environment; code wins.
| Option | Environment | Default |
|---|---|---|
key | POSTHOG_KEY | none: reporting is off |
host | POSTHOG_HOST | https://us.i.posthog.com (use https://eu.i.posthog.com for EU Cloud) |
release | POSTHOG_RELEASE | none; set it to the commit a build is from |
interval_ms | 10000 (at least 100) |
Without a key nothing is kept or sent, as you want while developing. At start, the server logs where errors go, or that reporting is off.
Issues#
PostHog groups errors into issues, usually by their stack trace. Roc has no stack traces, so the package tells PostHog which issue each error belongs to (its $exception_fingerprint):
- a 5xx answer, by its route's pattern and its message;
- a captured error, by its message alone, so it is one issue wherever it happens;
- a failed job, by its kind and its error;
- a browser's error, by its type and message.
Parts that change between occurrences are taken out first: any word with a digit counts as the same (user 1234 not found and user 77 not found are one issue), and so does text in double quotes or backticks.
So a loop of errors can't flood the project, one issue is sent at most 20 times a minute, all browsers together send at most 120 errors a minute, and each page load at most 10. A batch PostHog doesn't take (a 5xx, or no answer) is sent again next time; one it refuses (a 4xx, such as a wrong key) is dropped, and the log says so.
A daily digest#
PostHog's MCP server lists the issues and how many people each reached. A scheduled agent can read it once a day, write a digest of what is new or came back, and for each top issue check out its release, write a failing test from its route, method and fields, fix the bug on a branch and open a pull request for a person to review. The package's README has the steps.
Not reported#
- A crash in Roc while answering a request. It ends the call before the middleware sees an answer; the host answers 500 and logs
rocx server: Roc crashed. (A job that crashes is reported: to the jobs plugin, a crash is a failure.) - Some failures in the browser. A computation that fails with no
<Errored>around it, and a handler that fails, are written to the browser's console by the runtime and never reach the script.