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

📚 Interview question

How should an API design its error responses? Explain ProblemDetails (RFC 9457) and its fields, how you represent validation errors, why you would define a catalogue of stable error codes, how you avoid leaking internals, and how you keep errors consistent across many services.

Error response design: RFC 9457 ProblemDetails fields and extensions, validation error shape, a stable error-code catalogue, hiding internals with a trace id, and consistency across services and gateways.

Intermediate Theory Intermediate api-design aspnet-core error-handling problem-details rfc-9457 web-api

🎯 Key points

  • RFC 9457 (July 2023, obsoletes RFC 7807, same JSON shape): type, title, status, detail, instance, plus extensions
  • Media type application/problem+json for every 4xx/5xx
  • type is a stable URI per error kind; title is constant per type; detail is occurrence-specific
  • Validation: 400 with an errors map of JSON field path to messages (ValidationProblemDetails); RFC 9457 also allows several problems of one type in an extension array
  • Stable machine-readable error codes in an extension (e.g. code: ORDER_ALREADY_SHIPPED) clients switch on
  • No stack traces, SQL or exception messages; return a traceId and log details server-side
  • Correct status codes still matter; never 200 with an error body
  • Consistency via a shared package, AddProblemDetails, gateway policies and API guidelines

⏱ 30-second answer

I return ProblemDetails (RFC 9457, which replaced RFC 7807 in 2023) with Content-Type: application/problem+json. Its fields are type (a stable URI identifying the error kind), title (a constant summary for that type), status, detail (this occurrence) and instance, plus extensions.

  • Validation errors: 400 with an errors map from field to messages.
  • Business errors: a stable machine-readable code from a published catalogue, like ORDER_ALREADY_SHIPPED, so clients branch on codes, not message text.
  • No internals: no stack traces or SQL; return a traceId and log the detail.

Consistency comes from one shared configuration (AddProblemDetails, exception handler) and API guidelines. The trade-off: a code catalogue is a contract you must maintain, but it's what lets clients handle errors reliably.

🗣 Full answer (senior)

How I would answer this in an interview

"Errors are part of the API contract, and clients write more code around errors than around success. So I standardise on ProblemDetails, defined by RFC 9457, which obsoleted RFC 7807 in 2023 but kept it compatible. A problem response has the application/problem+json media type and five standard members: type, a URI that identifies the kind of problem and ideally points at documentation; title, a short summary that stays the same for that type; status, mirroring the HTTP status; detail, a human explanation of this occurrence; and instance, identifying this occurrence. Anything else goes in extension members.

On top of that I add two extensions everywhere: traceId, from the W3C trace context so support can find the request in Application Insights, and a stable code from an error catalogue, like ORDER_ALREADY_SHIPPED or PAYMENT_DECLINED. Clients switch on code, never on detail text, so we can reword messages or translate them without breaking anybody. Validation failures are a 400 with an errors dictionary from field name to messages, which is what ValidationProblemDetails in ASP.NET Core produces, and field names use the same casing as the JSON body.

The mistake I see is leaking internals: returning ex.Message, a stack trace or a SQL error to the client. That's an information disclosure finding in every penetration test, and under the Privacy Act it can even leak personal data from the failing query. The client gets a generic 500 problem with the trace id; the details go to the logs. The other mistake is inconsistency: each service invents its own shape, so the mobile team writes five error parsers. I fix that once, in a shared package and the API guidelines, not service by service."


ProblemDetails members (RFC 9457)

Member Meaning Example
type URI identifying the problem type; defaults to about:blank https://errors.example.com.au/order-already-shipped
title Short summary, constant for the type Order already shipped
status HTTP status code (advisory copy) 409
detail Explanation of this occurrence, for humans Order 4821 shipped on 18 Nov and can't be cancelled.
instance URI for this occurrence /v1/orders/4821/cancellation
extensions Anything else code, traceId, errors, retryAfter

Example responses

HTTP/1.1 409 Conflict
Content-Type: application/problem+json

{
  "type": "https://errors.example.com.au/order-already-shipped",
  "title": "Order already shipped",
  "status": 409,
  "detail": "Order 4821 shipped on 18 Nov 2026 and can't be cancelled.",
  "instance": "/v1/orders/4821/cancellation",
  "code": "ORDER_ALREADY_SHIPPED",
  "traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
}
HTTP/1.1 400 Bad Request
Content-Type: application/problem+json

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "code": "VALIDATION_FAILED",
  "errors": {
    "email": ["Email is required."],
    "items[0].quantity": ["Quantity must be between 1 and 99."]
  },
  "traceId": "00-..."
}

What goes where

Information Client response Server logs
Error kind (type, code) Yes Yes
Human message (detail) Yes, safe text Yes
Trace id Yes Yes
Exception type, stack trace, SQL No Yes
Personal data of other users Never Only if needed and permitted

Production example

We had [six] services returning four different error shapes; the mobile app had a parser per service and showed "Something went wrong" for most failures. A shared ProblemDetails package with a 40-entry code catalogue let the app map codes to specific messages. Support tickets that said only "error" dropped by [about a third] because users saw actionable text, and every ticket now quoted a trace id.

🔍 What the interviewer is checking

Checks that the candidate designs errors as a contract: standard format, stable codes, safe content and consistency.

Green flags

  • Names RFC 9457 and its members, and application/problem+json
  • Separates stable code/type from human detail
  • Returns a trace id and keeps stack traces out
  • Thinks about consistency across services and the gateway

Red flags

  • 200 with an error flag
  • Exception messages returned to clients
  • Clients expected to parse message text

📚 Learn in depth

1. From RFC 7807 to RFC 9457

RFC 7807 (2016) defined Problem Details. RFC 9457 (July 2023) obsoletes it with small changes: clearer guidance on type URIs, a way to represent multiple problems of the same type in one response, and an IANA registry of common problem types. The JSON format is unchanged, so existing clients keep working. When interviewers say "7807" they mean the same thing.

2. How ASP.NET Core produces it

exception thrown ──► UseExceptionHandler ──► IExceptionHandler(s) ──┐
                                                                        ▼
empty 4xx/5xx  ──► UseStatusCodePages ──► IProblemDetailsService ──► writer ─► application/problem+json
                                                    ▲
Results.Problem / TypedResults.ValidationProblem ──┘
                                (CustomizeProblemDetails runs for all of them)

AddProblemDetails(o => o.CustomizeProblemDetails = ...) is the one place to add traceId, code defaults or an instance. In development the exception handler can include exception details; in production it must not.

3. Designing type and code

  • type is a URI. It doesn't have to resolve, but if it does, put the documentation there: cause, how to fix, whether to retry.
  • title is constant for a type; don't put ids in it.
  • code is a short, stable, SCREAMING_SNAKE identifier. It duplicates the information in type, but clients find a short string easier to switch on, and it survives if your docs domain changes.
  • The catalogue lists each code with its status, meaning, whether it's retryable and the client action.
code status retryable client action
VALIDATION_FAILED 400 No Fix input, show errors
ORDER_ALREADY_SHIPPED 409 No Offer return instead
CONCURRENCY_CONFLICT 412 After refetch Reload and reapply
RATE_LIMITED 429 Yes, after Retry-After Back off
DEPENDENCY_UNAVAILABLE 503 Yes Retry with jitter

4. Validation errors

The errors member isn't in the RFC; it's an ASP.NET Core convention (ValidationProblemDetails) that has become the de facto standard. Keys should match the JSON path the client sent (items[0].quantity), using the same camelCase as the payload. RFC 9457 also suggests representing several problems of one type as an array in an extension, which is another valid shape; pick one in your guidelines.

5. Not leaking internals

Information disclosure (OWASP API Security Top 10 includes security misconfiguration and verbose errors) gives attackers table names, library versions and file paths. Under the Australian Privacy Act, a SQL error echoing a row can disclose personal information. Rules: generic detail for 5xx, specific detail only for errors the client caused and can fix, never echo other users' data, and log the full exception with the same trace id.

6. Consistency across services

  • A shared NuGet package that configures AddProblemDetails, the exception handler and the code catalogue types.
  • API guidelines that mandate problem+json for every 4xx/5xx.
  • The gateway (Azure API Management) uses policies to convert its own errors (401 from JWT validation, 429 from rate limiting) to the same shape.
  • Contract tests assert the error shape for each endpoint's documented errors.

Try it yourself

  1. Add AddProblemDetails with a CustomizeProblemDetails that adds traceId, throw an exception and inspect the 500 response in Development and Production.
  2. Post an invalid body to a Minimal API with .NET 10 validation and look at the errors keys.
  3. Write an IExceptionHandler that maps a domain exception to a 409 with a code.
  4. Search your logs for the trace id from the response and confirm the stack trace is there but not in the body.
  5. Write a contract test that every non-2xx response has Content-Type: application/problem+json.

💻 Code

One configuration that makes every error a ProblemDetails with traceId and a stable code, and maps domain errors without leaking internals.

// 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 in Application Insights.
    ctx.ProblemDetails.Extensions["traceId"] =
        Activity.Current?.Id ?? ctx.HttpContext.TraceIdentifier;
    ctx.ProblemDetails.Instance ??= ctx.HttpContext.Request.Path;
    // Default codes for framework-produced problems.
    ctx.ProblemDetails.Extensions.TryAdd("code", ctx.ProblemDetails.Status switch
    {
        400 => "VALIDATION_FAILED",
        401 => "UNAUTHENTICATED",
        403 => "FORBIDDEN",
        404 => "NOT_FOUND",
        429 => "RATE_LIMITED",
        _ => "INTERNAL_ERROR"
    });
});
builder.Services.AddExceptionHandler<DomainExceptionHandler>();
builder.Services.AddValidation(); // .NET 10 Minimal API validation -> ValidationProblem

var app = builder.Build();
app.UseExceptionHandler();   // unhandled exceptions -> problem+json, no stack trace in Production
app.UseStatusCodePages();    // empty 404/405 -> problem+json

app.MapPost("/v1/orders/{id:int}/cancellation", (int id) =>
{
    // Simulate a business rule failure.
    throw new DomainException("ORDER_ALREADY_SHIPPED", StatusCodes.Status409Conflict,
        "Order already shipped", $"Order {id} has shipped and can't be cancelled.");
});

app.Run();

public sealed class DomainException(string code, int status, string title, string detail)
    : Exception(detail)
{
    public string Code { get; } = code;
    public int Status { get; } = status;
    public string Title { get; } = title;
}

// Maps known business errors; anything else falls through to a generic 500.
public sealed class DomainExceptionHandler(IProblemDetailsService problems) : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext http, Exception exception, CancellationToken ct)
    {
        if (exception is not DomainException e) return false;

        http.Response.StatusCode = e.Status;
        return await problems.TryWriteAsync(new ProblemDetailsContext
        {
            HttpContext = http,
            Exception = exception,
            ProblemDetails = new ProblemDetails
            {
                Type = $"https://errors.example.com.au/{e.Code.ToLowerInvariant().Replace('_', '-')}",
                Title = e.Title,       // constant per type
                Status = e.Status,
                Detail = e.Message,    // safe, client-actionable text only
                Extensions = { ["code"] = e.Code }
            }
        });
    }
}

⚠ Common mistakes

  • Mistake: Returning 200 with { "success": false }. Why it is wrong: Clients, gateways, retries and monitoring all rely on the status code. Instead: Use the correct 4xx/5xx with a ProblemDetails body.
  • Mistake: Putting ex.Message or a stack trace in detail. Why it is wrong: It leaks internals and sometimes personal data, and fails penetration tests. Instead: Generic text for 5xx, log the exception, return a traceId.
  • Mistake: Clients parsing detail or title text. Why it is wrong: Any rewording or translation breaks them. Instead: Publish stable code values and type URIs to switch on.
  • Mistake: Putting variable data in title. Why it is wrong: RFC 9457 says title is constant per type; it breaks grouping in dashboards. Instead: Variable details go in detail or extensions.
  • Mistake: Writing error bodies by hand with Results.Json(...), which sends application/json. Why it is wrong: Clients and tools can't tell an error document from a resource. Instead: Always send application/problem+json by letting IProblemDetailsService (or Results.Problem) write the response.
  • Mistake: Validation error keys that don't match the request's JSON naming (for example PascalCase C# property names when the body is camelCase). Why it is wrong: Clients can't map errors back to fields. Instead: Use the same camelCase JSON paths the client sent, such as items[0].quantity.
  • Mistake: Each service and the gateway using a different error shape. Why it is wrong: Clients write a parser per source. Instead: A shared package (problem configuration, exception handler, code constants), API guidelines, and API Management policies that rewrite gateway errors.

🏛 Senior insight: trade-offs

The error catalogue is the part most teams skip and most clients need. A status code tells a client which family of thing went wrong; a stable code tells it what to do. I keep the catalogue small, add a code only when a client would act differently on it, and document retryability next to each one, because that's what drives client resilience logic.

Option When it fits Cost When not to
Plain ProblemDetails, type only Small internal APIs Clients compare URIs Many clients and many error kinds
ProblemDetails + code catalogue Public, partner and mobile APIs Catalogue governance Prototypes
Custom envelope ({ error: { code, message } }) Legacy clients already depend on it Non-standard; tooling doesn't understand it New APIs
Localised detail via Accept-Language Consumer apps showing server text Translation workflow When clients map codes to their own text anyway

I measure error quality by how many support tickets include a trace id and by the share of 4xx responses with a specific code rather than a generic one.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions AddProblemDetails or the exception handler Why: Checks the ASP.NET Core mechanics: IProblemDetailsService, status code pages and UseExceptionHandler.
    How to 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.

  2. When: Candidate discusses which status code goes with which error Why: Checks status code choice (400 vs 422, 409 vs 412) behind the problem body.
    How to answer

    The status code tells clients and infrastructure what happened before they read the body, so it must be exact.

    • Success: 200 OK with a body, 201 Created plus a Location header, 202 Accepted for work that finishes later, 204 No Content when there's nothing to return.
    • Client errors: 400 bad input, 422 well-formed but semantically invalid, 401 not authenticated vs 403 not allowed, 404 not found vs 410 gone, 409 conflicts with current state, 412 a precondition like If-Match failed, 429 rate limited with Retry-After.
    • Server errors: 500 our bug, 502 bad upstream response, 503 temporarily unavailable, 504 upstream timeout.

    The trade-off is precision versus consistency: pick a small, documented set and use it the same way in every service.

  3. When: Candidate talks about validation errors and the errors map Why: Checks where validation runs and how it produces ValidationProblemDetails.
    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.

↩ Usually asked after

More in API Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me