📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is ProblemDetails (RFC 9457), and how do you return consistent error responses in ASP.NET Core? Explain AddProblemDetails, IProblemDetailsService, status code pages, how UseExceptionHandler uses them, and how you add a trace id and your own error codes.

ProblemDetails in ASP.NET Core .NET 10: the RFC 9457 shape (type, title, status, detail, instance, extensions), ValidationProblemDetails, AddProblemDetails and CustomizeProblemDetails, IProblemDetailsService and IProblemDetailsWriter, UseStatusCodePages for empty error responses, UseExceptionHandler and IExceptionHandler integration, adding traceId and stable error codes, and not leaking internals.

Mid-Level Theory Intermediate api-design aspnet-core error-handling problem-details rfc-9457 status-code-pages

🎯 Key points

  • RFC 9457 (2023) formally obsoletes RFC 7807 but keeps the same backward-compatible application/problem+json format: type, title, status, detail, instance and extension members
  • ValidationProblemDetails adds an errors dictionary keyed by field for 400s (used by [ApiController] and .NET 10 Minimal API validation)
  • AddProblemDetails registers IProblemDetailsService; UseExceptionHandler, UseStatusCodePages and the developer exception page use it to write bodies
  • UseStatusCodePages turns empty 4xx/5xx responses (e.g. 404 from routing, 401 from auth) into ProblemDetails
  • CustomizeProblemDetails adds extensions such as traceId (Activity.Current?.Id) and instance to every problem
  • IExceptionHandler maps known exceptions to specific status codes and stable error codes; unknown ones become a generic 500
  • Log the exception with the same trace id that goes to the client; never put stack traces, SQL or exception messages in production responses
  • Use one error shape everywhere; request-pipeline handlers don't cover BackgroundService or queue consumers, which need their own logging and failure handling

⏱ 30-second answer

ProblemDetails is the standard JSON shape for HTTP API errors, defined by RFC 9457 (which replaced RFC 7807): type, title, status, detail, instance, plus extension members, served as application/problem+json. ValidationProblemDetails adds an errors dictionary per field. In ASP.NET Core, AddProblemDetails() registers IProblemDetailsService, which the framework uses wherever it writes an error body: UseExceptionHandler for unhandled exceptions, UseStatusCodePages for empty 404s/401s, and the developer exception page. CustomizeProblemDetails adds a traceId and anything else to every response; an IExceptionHandler maps known exceptions to specific codes with a stable errorCode extension. The trade-off: one consistent contract for every error, but you must make sure no internal detail leaks.

🗣 Full answer (senior)

How I would answer this in an interview

"ProblemDetails is the IETF standard for error bodies in HTTP APIs. RFC 7807 introduced it and RFC 9457 replaced it in 2023 with clarifications and a registry for common types. The body is application/problem+json with type, a URI identifying the kind of problem, title, status, detail for this occurrence, instance, and any extension members you need. For validation there's the ValidationProblemDetails variant with an errors dictionary keyed by field name.

In ASP.NET Core I call builder.Services.AddProblemDetails(). That registers IProblemDetailsService, and from then on the framework writes ProblemDetails everywhere it produces an error: UseExceptionHandler for unhandled exceptions, UseStatusCodePages for responses that have an error status but no body, like a 404 from routing or a 401 from authentication, [ApiController] for validation and client errors, and .NET 10 Minimal API validation. In CustomizeProblemDetails I add a traceId from Activity.Current?.Id and the request path as instance, so a support person can paste the trace id into Application Insights and land on the exact request. For known failures I write an IExceptionHandler that maps, say, ConcurrencyException to 409 with an errorCode of order.concurrency_conflict, and returns false for anything else so the default handler produces a generic 500.

For example, [at company] our [mobile app] parsed four different error shapes: HTML error pages from IIS, empty 404s, our own { success: false } JSON and ProblemDetails from validation. We standardised on ProblemDetails with stable error codes and a trace id, and [the app team deleted their per-endpoint error parsing and support tickets with 'unknown error' dropped noticeably]. The mistake I see is putting exception.Message in detail in production; that's how connection strings and SQL leak. The client gets a code and a trace id; the details stay in the logs."


The shape

Member Meaning Example
type URI identifying the problem type https://errors.example.com.au/order/concurrency-conflict
title Short, stable summary for the type Order was modified by someone else
status HTTP status code 409
detail This occurrence, safe for clients Reload the order and try again.
instance This occurrence's URI /orders/42
extensions Anything else traceId, errorCode, errors

Who writes ProblemDetails

Source Needs
Unhandled exception UseExceptionHandler() + AddProblemDetails() (+ optional IExceptionHandler)
Empty 4xx/5xx (404, 401, 405) UseStatusCodePages() + AddProblemDetails()
Invalid model (controllers) [ApiController]
Invalid parameters (Minimal APIs, .NET 10) AddValidation()
Your handlers TypedResults.Problem(...), TypedResults.ValidationProblem(...), Problem() in controllers

Production example

After adding traceId to every ProblemDetails, the median time for support to locate a failing request in Application Insights went from about 20 minutes of searching by time and user to under a minute, and a security review confirmed no exception messages or stack traces appeared in production responses.

🔍 What the interviewer is checking

Checks whether the candidate can design a consistent, safe error contract using the framework's built-in pieces.

Green flags

  • Knows RFC 9457 and the ProblemDetails members.
  • Wires AddProblemDetails, UseExceptionHandler and UseStatusCodePages together.
  • Adds a trace id and stable error codes.
  • Refuses to leak exception details in production.

Red flags

  • Returns 200 with an error flag.
  • Puts stack traces in responses.
  • Has a different error shape per endpoint.

📚 Learn in depth

1. The services

AddProblemDetails()
  ├─ IProblemDetailsService      (picks a writer and writes)
  ├─ IProblemDetailsWriter[]     (default JSON writer; add your own for other formats)
  └─ ProblemDetailsOptions.CustomizeProblemDetails (runs for every problem)

IProblemDetailsService.TryWriteAsync(new ProblemDetailsContext { HttpContext, ProblemDetails, Exception }) asks each writer CanWrite (based on the Accept header) and writes the first match. Framework components call this; you can too.

2. Exception handling

Request ─► UseExceptionHandler ─► ... ─► endpoint throws
                   │
                   ▼
   IExceptionHandler[] in registration order: TryHandleAsync → true stops the chain
                   │ (none handled)
                   ▼
   IProblemDetailsService writes a 500 ProblemDetails (no exception details outside Development)

UseExceptionHandler() without a path requires AddProblemDetails() or an IExceptionHandler, otherwise it throws at start-up. In Development, WebApplication adds the developer exception page automatically, which also writes ProblemDetails (including exception details) when the client accepts JSON.

3. Status code pages

UseStatusCodePages() hooks responses that finish with a status of 400–599 and no body (and haven't started). With AddProblemDetails() registered, it writes ProblemDetails; otherwise plain text. It doesn't touch responses that already have a body.

4. Defaults in the type field

The framework fills type with links to the relevant RFC 9110 section for standard status codes (via ClientErrorMapping in MVC and the default writer), and title with the reason phrase. Your own problem types should have stable, documented URIs.

5. Trace id

Use Activity.Current?.Id (the W3C traceparent id that Application Insights and OpenTelemetry use) with HttpContext.TraceIdentifier as a fallback. [ApiController] validation responses already include traceId; adding it in CustomizeProblemDetails makes every error consistent.

6. Security

The Privacy Act's APP 11 and OWASP guidance both point the same way: error responses must not reveal personal information or internals. Stack traces, SQL text, server names and exception messages belong in logs, correlated by trace id.

Try it yourself

  1. Call a non-existent route with and without UseStatusCodePages + AddProblemDetails and compare.
  2. Throw from an endpoint in Development and Production and compare the bodies.
  3. Add CustomizeProblemDetails with traceId and find the request in Application Insights by that id.
  4. Write an IExceptionHandler for a domain exception and check that other exceptions still produce a generic 500.
  5. Send Accept: application/xml and see which writer runs.

💻 Code

Consistent ProblemDetails for exceptions, empty status codes and domain errors, with a trace id and stable error codes.

// Program.cs
using System.Diagnostics;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddProblemDetails(o => o.CustomizeProblemDetails = ctx =>
{
    // Every problem gets a trace id support can search for, and the request path
    ctx.ProblemDetails.Extensions["traceId"] = Activity.Current?.Id ?? ctx.HttpContext.TraceIdentifier;
    ctx.ProblemDetails.Instance ??= $"{ctx.HttpContext.Request.Method} {ctx.HttpContext.Request.Path}";
});
builder.Services.AddExceptionHandler<DomainExceptionHandler>(); // known exceptions -> specific codes

var app = builder.Build();

app.UseExceptionHandler();   // unhandled exceptions -> ProblemDetails (generic 500 if not handled above)
app.UseStatusCodePages();    // empty 404/401/405 -> ProblemDetails

app.MapPut("/orders/{id:int}", (int id) =>
    id == 42 ? throw new ConcurrencyConflictException(id) : TypedResults.NoContent());

app.MapGet("/orders/{id:int}", (int id) => id > 1000
    ? TypedResults.Problem(title: "Order not found", statusCode: 404,
        type: "https://errors.example.com.au/order/not-found",
        extensions: new Dictionary<string, object?> { ["errorCode"] = "order.not_found" })
    : Results.Ok(new { id }));

app.Run();

public sealed class ConcurrencyConflictException(int orderId) : Exception($"Order {orderId} was modified concurrently.")
{
    public int OrderId { get; } = orderId;
}

public sealed class DomainExceptionHandler(IProblemDetailsService problems, ILogger<DomainExceptionHandler> logger) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext http, Exception exception, CancellationToken ct)
    {
        if (exception is not ConcurrencyConflictException conflict) return false; // let the default 500 handle it

        logger.LogWarning(exception, "Concurrency conflict on order {OrderId}", conflict.OrderId);
        http.Response.StatusCode = StatusCodes.Status409Conflict;
        return await problems.TryWriteAsync(new ProblemDetailsContext
        {
            HttpContext = http,
            Exception = exception,
            ProblemDetails = new ProblemDetails
            {
                Status = StatusCodes.Status409Conflict,
                Type = "https://errors.example.com.au/order/concurrency-conflict",
                Title = "Order was modified by someone else",
                Detail = "Reload the order and try again.",        // safe text, not exception.Message
                Extensions = { ["errorCode"] = "order.concurrency_conflict" }
            }
        });
    }
}
{
  "type": "https://errors.example.com.au/order/concurrency-conflict",
  "title": "Order was modified by someone else",
  "status": 409,
  "detail": "Reload the order and try again.",
  "instance": "PUT /orders/42",
  "errorCode": "order.concurrency_conflict",
  "traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
}

⚠ Common mistakes

  • Mistake: Putting exception.Message or stack traces in detail in production. Why it is wrong: It leaks SQL, connection details and personal data, and helps attackers. Instead: Safe, fixed text plus a trace id; details in logs.
  • Mistake: Calling UseExceptionHandler() without AddProblemDetails() or a path. Why it is wrong: It throws at start-up (or writes nothing useful). Instead: Register AddProblemDetails().
  • Mistake: Forgetting UseStatusCodePages. Why it is wrong: 404s from routing and 401s from authentication have empty bodies, so clients see a different shape. Instead: Add it so empty error responses become ProblemDetails.
  • Mistake: Mixing error shapes: ProblemDetails from validation, a custom { success, message } envelope from some handlers, HTML from the proxy. Why it is wrong: Every client needs several parsers and monitoring can't group errors. Instead: Route every error through IProblemDetailsService or TypedResults.Problem, and configure the proxy or gateway to pass API errors through.
  • Mistake: Returning 200 with { success: false }. Why it is wrong: Breaks HTTP semantics, caches, retries and monitoring; 'errors' look like successes in dashboards. Instead: Proper status codes with ProblemDetails.
  • Mistake: Expecting UseExceptionHandler to catch failures in BackgroundServices or message consumers. Why it is wrong: They run outside the request pipeline, so exceptions there are never turned into ProblemDetails and may stop the host. Instead: Catch, log with the trace id and retry or dead-letter in the worker itself.
  • Mistake: Using title for per-occurrence text. Why it is wrong: title should be stable per type; clients and dashboards group by it. Instead: Put occurrence details in detail.
  • Mistake: Clients parsing detail text to decide behaviour. Why it is wrong: Wording changes break clients. Instead: Provide a stable errorCode or type URI.

🏛 Senior insight: trade-offs

Error responses are part of the API contract and deserve the same design care as success responses. A senior sets up the whole chain once (AddProblemDetails, UseExceptionHandler, UseStatusCodePages, CustomizeProblemDetails, a few IExceptionHandlers for known domain failures) so every endpoint gets consistent errors for free, documents the type URIs and errorCode values, and makes the trace id the bridge between a client's error and the logs. Measure success by fewer 'unknown error' tickets and faster incident triage.

Option When it fits Cost When not to
Framework defaults (AddProblemDetails) Every API None Never skip
CustomizeProblemDetails (traceId, instance) Every API Trivial n/a
IExceptionHandler per domain exception family Known failures with meaningful codes Mapping code Control flow for expected outcomes (prefer results)
Result types returning TypedResults.Problem Expected business failures Slightly more code Truly exceptional conditions
Custom error envelope Legacy clients that can't change Non-standard, more docs New APIs

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions UseExceptionHandler or IExceptionHandler. Why: Checks the wider global exception strategy, including exceptions outside requests.
    How to answer

    In ASP.NET Core, register AddProblemDetails(), one or more IExceptionHandler implementations (.NET 8+) with AddExceptionHandler<T>(), and app.UseExceptionHandler() early in the pipeline. Handlers log once and map known exceptions to the right status code and an RFC 9457 ProblemDetails body, and never leak stack traces in production. For the process as a whole, AppDomain.CurrentDomain.UnhandledException is a last-chance notification: you can log and flush, but the process still terminates. TaskScheduler.UnobservedTaskException fires when a faulted task that nobody awaited is garbage-collected; it does not crash the process by default. In a BackgroundService, an unhandled exception in ExecuteAsync stops the host by default (.NET 6+). async void exceptions go to the synchronisation context and usually crash the process, so avoid async void except for event handlers.

  2. When: Candidate mentions the errors dictionary for 400s. Why: Checks how validation errors use ValidationProblemDetails consistently.
    How to answer

    I validate input at the edge and business rules in the application or domain layer. For input, DataAnnotations ([Required], [Range], [StringLength]) and IValidatableObject on request DTOs are the baseline. In controllers, binding fills ModelState and [ApiController] returns a 400 ValidationProblemDetails before the action runs. In Minimal APIs on .NET 10, builder.Services.AddValidation() uses a source generator to validate parameters and return the same 400 ProblemDetails; before .NET 10 you needed a filter. FluentValidation is my choice for complex, conditional or async rules; I call it explicitly or from a filter, because its automatic MVC integration is deprecated. Business rules like stock levels or uniqueness are checked where the data lives and returned in the same error shape. The trade-off: attributes are simple and visible in OpenAPI; code-based validators are more expressive.

🛠 Real-world problems: how you handle them

Four different error shapes broke the mobile app's error handling
Situation
A customer-facing API [at company] behind [Azure Front Door] served a [mobile app with ~200,000 users]. Errors came back as IIS HTML pages, empty 404s, a custom `{ success: false, message }` envelope and ProblemDetails from validation.
Signals
The app showed 'Something went wrong' for most failures; support tickets lacked anything to search by; a security scan flagged a 500 response containing a SQL Server error message with a table name.
Investigation
Catalogued error responses with an integration test that hit every endpoint with bad input, missing auth and forced failures; found the custom envelope in [30] actions, no `UseStatusCodePages`, and a catch block returning `ex.Message`.
Resolution
Immediately removed `ex.Message` from responses. Then added `AddProblemDetails` with `traceId`, `UseExceptionHandler` with `IExceptionHandler`s for [four] domain exception types, `UseStatusCodePages`, and replaced the custom envelope with `TypedResults.Problem` and documented `errorCode`s, behind a version flag for older app builds.
Prevention
A contract test asserting every non-2xx response is `application/problem+json` with a `traceId`; a security test that fails if responses contain stack trace or SQL patterns; an error catalogue page in the API docs.

How to tell it (STAR)

**S:** Our [mobile API] returned four different error shapes and a scan found a SQL error message leaking in a 500. **T:** I owned standardising errors without breaking older app versions. **A:** I removed the leak first, then wired AddProblemDetails, UseExceptionHandler with a few IExceptionHandlers, and UseStatusCodePages, added trace ids and stable error codes, and added contract tests for every non-2xx response. **R:** The app team removed per-endpoint error parsing, 'unknown error' tickets [dropped by about half], and support could find any failing request by trace id in under a minute.

↩ Usually asked after

More in Request Handling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me