wasAsked.

How do you handle errors and logging in your API ?

Capgemini · Full Stack Developer · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

A good answer covers both parts: consistent error responses for clients and useful, safe logs for the team. Error handling 1. Global exception handling - UseExceptionHandler with IExceptionHandler (.NET 8+) catches unhandled exceptions centrally, logs them once, and returns a safe response — no stack traces in production. - Known exception types map to status codes: NotFoundException to 404, ValidationException to 400, ConflictException (and concurrency exceptions) to 409, and unexpected errors to 500. 2. Consistent error format - RFC 7807/9457 Problem Details (AddProblemDetails) for all errors, including a traceId so users and support can reference the failure. - [ApiController] returns ValidationProblemDetails automatically for invalid models; FluentValidation is often used for complex rules. 3. Expected failures without exceptions - Return results directly for expected outcomes (NotFound(), Conflict()) or use a Result pattern in services, reserving exceptions for unexpected situations. 4. Resilience - Timeouts, retries and circuit breakers for external calls (Microsoft.Extensions.Http.Resilience), with meaningful 503 responses when dependencies are down. Logging 1. Structured logging - ILogger with message templates: _logger.LogInformation("Order {OrderId} created for {CustomerId}", id, customerId); — the values become searchable fields. - Serilog or the built-in providers, writing JSON to a central platform: Application Insights, Seq, Elasticsearch or Grafana Loki. 2. Correlation - Every log entry includes the trace ID and span ID (OpenTelemetry / Activity), so you can see all logs for one request across services. - Logging scopes add context such as tenant ID or order ID. 3. Log levels used deliberately - Information for important business events, Warning for unusual but handled situations, Error for failures needing attention, Debug or Trace for diagnostics (disabled in production by default). - Configure levels per category in appsettings.json to reduce noise (for example Microsoft.AspNetCore at Warning). 4. Safety and cost - Never log passwords, tokens, card numbers or unnecessary personal data; mask sensitive fields. - Avoid logging huge payloads; use sampling for high-volume telemetry. Monitoring - Dashboards for error rates and latency, and alerts on spikes (Azure Monitor alerts, Grafana). - Request logging (UseHttpLogging, or OpenTelemetry request telemetry) for HTTP-level visibility. Example summary: "Unhandled exceptions go through a global handler that logs with structured context and returns Problem Details with a trace ID; logs and traces flow to Application Insights via OpenTelemetry, and we alert on error-rate increases."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics