Introduction
A REST API is not reliable merely because it returns correct data when everything goes well. It must also handle invalid input, missing resources, business-rule violations, and unexpected infrastructure failures in a predictable and secure way. A malformed email address, an empty product name, a duplicate SKU, and a database outage should not all produce the same response.
In the previous lessons, we created controllers, CRUD endpoints, and HTTP responses. In this lesson, we will make those endpoints more robust. We will validate incoming DTOs, represent expected business failures with dedicated exception types, and create global middleware that catches unhandled exceptions across the API pipeline. The result will be a consistent error contract that the web application and other clients can process reliably.
1. Thinking about errors by layer
Error handling should follow the responsibilities of the three-tier architecture:
- API layer: Receives HTTP requests, exposes validation failures, and translates application exceptions into HTTP responses.
- Business layer: Enforces application rules, such as preventing two products from using the same SKU.
- Data access layer: Performs database operations. SQL Server connectivity failures, constraint violations, and query errors may originate here.
Expected business situations should not be represented by an unclassified Exception everywhere. Dedicated exception types allow the API layer to map a missing resource to 404 Not Found, a duplicate value to 409 Conflict, and other invalid operations to an appropriate client error. Unexpected technical failures should be logged in detail on the server but exposed as a safe 500 Internal Server Error response.
2. Validating incoming models
Client JSON should not be treated as a domain entity without validation. Use request DTOs as the boundary of the API and define format-oriented rules there. The following request model validates required fields, string length, allowed SKU characters, and the price range:
using System.ComponentModel.DataAnnotations;
public sealed class CreateProductRequest
{
[Required(ErrorMessage = "Product name is required.")]
[StringLength(120, MinimumLength = 2,
ErrorMessage = "Product name must contain between 2 and 120 characters.")]
public string Name { get; init; } = string.Empty;
[Required(ErrorMessage = "SKU is required.")]
[RegularExpression("^[A-Z0-9-]+$",
ErrorMessage = "SKU may contain only uppercase letters, digits, and hyphens.")]
public string Sku { get; init; } = string.Empty;
[Range(typeof(decimal), "0.01", "999999.99",
ErrorMessage = "Price must be between 0.01 and 999999.99.")]
public decimal Price { get; init; }
}When a controller uses [ApiController], ASP.NET Core automatically produces a 400 Bad Request response when model binding or validation fails. The response commonly uses ValidationProblemDetails, which groups messages by property name so a client can associate an error with a specific input field.
[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
private readonly IProductService _productService;
public ProductsController(IProductService productService)
{
_productService = productService;
}
[HttpPost]
public async Task Create(
CreateProductRequest request,
CancellationToken cancellationToken)
{
var result = await _productService.CreateAsync(
request, cancellationToken);
return CreatedAtAction(
nameof(GetById),
new { id = result.Id },
result);
}
[HttpGet("{id:int}")]
public async Task GetById(
int id,
CancellationToken cancellationToken)
{
return Ok(await _productService.GetByIdAsync(
id, cancellationToken));
}
} Validation attributes should describe input shape and basic constraints. For example, a negative price can be rejected at the DTO boundary. Whether a SKU already exists requires application or database access, so that rule belongs in the service layer rather than in a simple attribute.
3. Representing business-layer failures
We will create custom exception classes for expected business outcomes. These classes belong in the application layer and should not depend on ASP.NET Core types such as HttpContext, ActionResult, or ControllerBase.
public abstract class ApplicationException : Exception
{
protected ApplicationException(string message) : base(message)
{
}
}
public sealed class ProductNotFoundException : ApplicationException
{
public ProductNotFoundException(int productId)
: base($"Product with ID {productId} was not found.")
{
ProductId = productId;
}
public int ProductId { get; }
}
public sealed class DuplicateSkuException : ApplicationException
{
public DuplicateSkuException(string sku)
: base($"SKU {sku} is already in use.")
{
Sku = sku;
}
public string Sku { get; }
}A service can throw these exceptions when a business rule is violated:
public async Task CreateAsync(
CreateProductRequest request,
CancellationToken cancellationToken)
{
var normalizedSku = request.Sku.Trim().ToUpperInvariant();
if (await _unitOfWork.Products.ExistsBySkuAsync(
normalizedSku, cancellationToken))
{
throw new DuplicateSkuException(normalizedSku);
}
var product = new Product
{
Name = request.Name.Trim(),
Sku = normalizedSku,
Price = request.Price
};
_unitOfWork.Products.Add(product);
await _unitOfWork.SaveChangesAsync(cancellationToken);
return _mapper.Map(product);
}This design avoids repeating similar try-catch blocks in every controller action. Controllers focus on HTTP concerns, while a single middleware translates known application failures consistently.
4. Building global exception middleware
Middleware runs inside the HTTP pipeline and can wrap the components that execute after it. A global exception middleware should perform four tasks:
- Call the next middleware or endpoint.
- Catch known exceptions and map them to suitable status codes.
- Log unexpected exceptions with enough context for diagnosis.
- Write a safe, machine-readable response without exposing sensitive implementation details.
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
public sealed class GlobalExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<GlobalExceptionMiddleware> _logger;
public GlobalExceptionMiddleware(
RequestDelegate next,
ILogger<GlobalExceptionMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception exception)
{
_logger.LogError(
exception,
"An error occurred while processing the request. TraceId: {TraceId}",
context.TraceIdentifier);
await WriteErrorResponseAsync(context, exception);
}
}
private static async Task WriteErrorResponseAsync(
HttpContext context,
Exception exception)
{
if (context.Response.HasStarted)
{
throw exception;
}
var statusCode = exception switch
{
ProductNotFoundException => StatusCodes.Status404NotFound,
DuplicateSkuException => StatusCodes.Status409Conflict,
ApplicationException => StatusCodes.Status400BadRequest,
_ => StatusCodes.Status500InternalServerError
};
var problem = new ProblemDetails
{
Status = statusCode,
Title = GetTitle(statusCode),
Detail = statusCode == StatusCodes.Status500InternalServerError
? "An unexpected error occurred."
: exception.Message,
Instance = context.Request.Path
};
problem.Extensions["traceId"] = context.TraceIdentifier;
context.Response.StatusCode = statusCode;
context.Response.ContentType = "application/problem+json";
await context.Response.WriteAsync(
JsonSerializer.Serialize(problem));
}
private static string GetTitle(int statusCode) => statusCode switch
{
400 => "Invalid request",
404 => "Resource not found",
409 => "Request conflict",
_ => "Server error"
};
}The Response.HasStarted check is important. Once response headers or body content have begun to reach the client, changing the status code may no longer be possible. Rethrowing in that situation allows the server to terminate the response according to its own behavior.
5. Registering the middleware
Register the middleware before controllers and endpoints that may throw exceptions:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddProblemDetails();
builder.Services.AddApplicationServices();
builder.Services.AddDataAccess(builder.Configuration);
var app = builder.Build();
app.UseMiddleware<GlobalExceptionMiddleware>();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();In production, never return the original exception message for unknown failures. Connection strings, table names, file paths, and stack traces can disclose implementation details. Return a generic message to the client and include a traceId that support staff can use to find the complete log entry.
6. ProblemDetails as a shared error contract
ProblemDetails provides a standard, machine-readable structure for HTTP API errors. A possible 409 response is:
{
"type": "https://httpstatuses.com/409",
"title": "Request conflict",
"status": 409,
"detail": "SKU ABC-100 is already in use.",
"instance": "/api/products",
"traceId": "00-abc123"
}For validation failures, ValidationProblemDetails is usually more useful because it contains an errors dictionary. A web client can read keys such as errors.Name or errors.Price and display the corresponding message beside the input. The response shape should remain stable across endpoints so clients do not need separate parsing logic for every controller.
7. Common mistakes
- Adding try-catch to every action: This creates duplication and often produces different error formats.
- Returning HTTP results from the application layer: This couples business code to ASP.NET Core. Prefer exceptions or application result objects.
- Returning 500 for every failure: Client mistakes and server failures should be distinguishable.
- Exposing raw exception messages: Technical details may reveal sensitive information.
- Mixing validation and business rules: Required fields and ranges belong at the request boundary; uniqueness and workflow rules belong in the service layer.
- Skipping structured logging: A safe client response is not enough if the server cannot diagnose the incident.
8. Short practice exercise
Extend the product API with the following tasks:
- Add Data Annotations for name, SKU, and price to
CreateProductRequest. - Create
ProductNotFoundExceptionandDuplicateSkuExceptionin the application layer. - Throw
ProductNotFoundExceptionwhen a requested product does not exist andDuplicateSkuExceptionwhen a SKU is already used. - Register the global middleware in the API project and map the exceptions to
404and409. - Send an invalid POST request, a GET request for a missing product, and a POST request with a duplicate SKU. Compare the three responses.
Also verify that every middleware-generated response includes a traceId and that an unexpected exception never sends a stack trace to the client.
Conclusion
This lesson introduced three mechanisms that significantly improve API reliability: DTO-based model validation, dedicated exception types for business rules, and global exception middleware around the HTTP pipeline. With ProblemDetails, clients can process validation, conflict, not-found, and server errors through a predictable contract.
The architecture is now ready for the next integration step. When the web application starts communicating with the REST API, it can map validation messages back to forms, show useful business feedback, and handle network or server failures without depending on controller-specific response formats.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling-api?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-10.0