$ cat docs/middleware/error-reporter.md
Error reporterRelator de erros
Get notified of crashes with a Sentry-compatible collector, while credentials and personal data stay out of the report.Seja avisado de falhas com um coletor compatível com Sentry, sem credenciais nem dados pessoais no relatório.
What it doesO que faz
errorReporter(options: ErrorReporterOptions): MiddlewareHandler. When the pipeline throws (except HttpError below 500), it builds a Sentry envelope (exception type and message, method, URL without query, headers, request id), cleans it with the @tupik/infra redaction (credentials, cookies, CPF... redacted at any depth, IPs masked) and posts it to the DSN after the response, with ctx.runtime.executionCtx.waitUntil on Workers. The error is rethrown to the app.
errorReporter(options: ErrorReporterOptions): MiddlewareHandler. Quando o pipeline lança (fora HttpError abaixo de 500), ele monta um envelope Sentry (tipo e mensagem da exceção, método, URL sem query, headers, id da requisição), limpa com a redação do @tupik/infra (credenciais, cookies, CPF... ocultados em qualquer profundidade, IPs mascarados) e envia ao DSN depois da resposta, com ctx.runtime.executionCtx.waitUntil no Workers. O erro é relançado para o app.
Install and orderInstalar e ordenar
pnpm add @tupik/middleware Register it with app.use, after requestId(), so it wraps every route.
Registre com app.use, depois do requestId(), para envolver todas as rotas.
ExampleExemplo
import { createApp } from '@tupik/core';
import { errorReporter, requestId } from '@tupik/middleware';
const app = createApp()
.use(requestId())
.use(errorReporter({
dsn: env.ERRORS_DSN, // https://<key>@errors.example.com/<project>
environment: 'production',
release: '1.4.2',
errorDetail: 'name', // drop messages that may carry user data
}));import { createApp } from '@tupik/core';
import { errorReporter, requestId } from '@tupik/middleware';
const app = createApp()
.use(requestId())
.use(errorReporter({
dsn: env.ERRORS_DSN, // https://<chave>@errors.example.com/<projeto>
environment: 'production',
release: '1.4.2',
errorDetail: 'name', // descarta mensagens que podem ter dado do usuário
})); APIAPI
| OptionOpção | TypeTipo | Default / behaviorPadrão / comportamento |
|---|---|---|
dsn | string | Required. https://<public key>@<host>[/<path>]/<project id>.Obrigatório. https://<chave pública>@<host>[/<caminho>]/<id do projeto>. |
environment, release | string | Absent. Copied to the event.Ausente. Copiados para o evento. |
redact | readonly string[] | Extra keys on top of DEFAULT_REDACT_KEYS.Chaves extras além de DEFAULT_REDACT_KEYS. |
errorDetail | 'name' | 'message' | 'message'. 'name' sends only the error class.'message'. 'name' envia só a classe do erro. |
sampleRate, shouldReport, fetch | number, fn, fn | 1, all but HttpError < 500, globalThis.fetch.1, todos menos HttpError < 500, globalThis.fetch. |
interface ErrorReporterOptions { dsn; environment?; release?; redact?; errorDetail?; sampleRate?; shouldReport?; fetch? }
interface ErrorReporterOptions { dsn; environment?; release?; redact?; errorDetail?; sampleRate?; shouldReport?; fetch? }
Errors and limitsErros e limites
- An invalid DSN or
sampleRateoutside 0 to 1 throws at creation. - Transport failures are swallowed; on Node and Bun the send is detached, so a crash right after can lose it.
- Errors answered by the engine before middleware (404, 413, validation) are not reported.
- DSN inválido ou
sampleRatefora de 0 a 1 lança na criação. - Falhas de envio são engolidas; em Node e Bun o envio é desacoplado, então uma queda logo depois pode perdê-lo.
- Erros respondidos pelo engine antes dos middlewares (404, 413, validação) não são relatados.
When not to use itQuando não usar
Error messages are kept by default and may still carry personal data the redaction cannot see; use errorDetail: 'name' where that matters. It sends no stack traces.
Mensagens de erro ficam por padrão e ainda podem levar dados pessoais que a redação não enxerga; use errorDetail: 'name' onde isso importa. Ele não envia stack traces.