Kest

Search

Search the documentation

Observability

Error monitoring

Find out about errors in production before your users tell you.

Every exception nobody handled becomes a 500 response and is written to the log. In production nobody reads the log all day, so you add an error monitor: a service that collects every error, groups the same error together, shows the stack trace and how many users it hit, and notifies you. Sentry is the best known; GlitchTip and self-hosted Sentry speak the same protocol.

Turn it on

Kest.run<AppModule> {
    import(SentryModule.forRoot {
        dsn = System.getenv("SENTRY_DSN")                    // https://<key>@<host>/<project>; blank in development sends nothing
        environment = "production"
        release = "1.4.2"
        tags = mapOf("team" to "payments")         // added to every event
        sampleRate = 1.0                           // the fraction of errors sent
    })
}

That is all for HTTP: every unhandled exception is sent with its stack trace (oldest call first, application frames marked), the request method, URL and headers, the environment and release.

What is reported automatically, and from where

Where the error happensReported?Tags you get
An HTTP controller (unhandled, becomes a 500)yesthe request: method, URL, headers (credentials removed)
A GraphQL resolver that throws something unexpectedyessource=graphql, path=/orders/total
A queue job that failed its last attemptyessource=queue, queue=emails, job=welcome, attempts=3
A scheduled task (@Cron, @Interval) that threwyessource=schedule, job=nightly-invoices
An event listener (@OnEvent async) that threwyessource=event, event=order.paid
A message-broker handler (@MessagePattern, @EventPattern)yessource=microservice, pattern=orders.create
A WebSocket message handleryessource=websocket, event=chat.send
An outbox message that gave up (dead letter)yessource=outbox, topic=order.created
A workflow that failedyessource=workflow, workflow=onboarding, run=...
A CQRS saga command that failedyessource=cqrs, saga=...
HttpExceptions (404, 400, 403, validation)no: they are the caller's mistakechange ignore to include them
Something you caught and handled with a filter or adviceno: you handled itcall capture if you still want to know

In Sentry you filter by tag: show me everything with source:queue.

Examples in each part of an application

A queue job. Nothing to write. When the last retry fails, it appears in Sentry with the queue and job name:

@Processor("emails")
class EmailProcessor(private val mail: Mailer) {
    @Process("welcome") fun welcome(data: WelcomeEmail) { mail.send(data.to, "welcome") }      // throws: Sentry gets it after the last attempt
}

A scheduled task:

@Injectable class Nightly(private val invoices: InvoiceService) {
    @Cron("0 0 2 * * *", name = "nightly-invoices") fun run() { invoices.sendAll() }     // an exception here: source=schedule, job=nightly-invoices
}

Something you caught yourself but still want to know about, with detail and the affected user:

@Injectable
class Checkout(private val sentry: SentryReporter, private val gateway: PaymentGateway) {
    fun pay(order: Order, user: User): Receipt = try {
        gateway.charge(order)
    } catch (e: GatewayTimeout) {
        sentry.capture(e,
            tags = mapOf("gateway" to "stripe", "plan" to user.plan),             // short labels you search by
            extra = mapOf("orderId" to order.id, "amountCents" to order.total),   // free-form detail shown on the event
            user = mapOf("id" to user.id, "email" to user.email))                 // Sentry counts how many users were hit
        Receipt.pending(order)                                                     // and you still answer the customer sensibly
    }
}

A message-broker handler needs nothing: an exception inside @MessagePattern("orders.create") is sent with pattern=orders.create, and the caller gets a generic 500 reply.

Protecting your users' data

  • Credentials are removed. Authorization, Cookie, Set-Cookie, X-Api-Key and Proxy-Authorization are never sent (redactedHeaders changes the list).
  • Clean anything else in beforeSend, which can edit or drop an event: beforeSend = { event -> event.remove("request"); event }, or return null to drop it.
  • The client never sees the message of an unexpected error, only "Internal server error".

It cannot slow or break your application

Events go through a bounded queue to a background sender. If Sentry is slow or down, requests are answered at once, the failure is counted (reporter.failed) and the oldest queued events are dropped (reporter.dropped, queueSize default 100). On shutdown Kest waits up to two seconds to send what is waiting.

Your own reporter

Send errors anywhere (Slack, email, a database). For HTTP errors implement ErrorReporter; for the other components register an ErrorHooks sink:

@Injectable
class SlackReporter(private val slack: SlackClient) : ErrorReporter {
    override fun report(error: Throwable, request: HttpRequest?) {
        slack.postAsync("#alerts", "${request?.method} ${request?.path}: ${error.message}")       // do not block: queue the work
    }
}
 
ErrorHooks.add { error, source, tags -> slack.postAsync("#alerts", "[$source] ${tags} ${error.message}") }   // queue, schedule, events, GraphQL ...

A reporter must not throw and should not block; if it throws, the exception is ignored and nothing else changes.

Not covered

Breadcrumbs, performance traces and user feedback are not sent: use OpenTelemetry for traces. Tested against a fake Sentry server (the envelope format, redaction, queue limits), not against sentry.io itself.

Read more