Custom exceptions represent specific error conditions in your domain, making error handling clearer and allowing global handlers to map them to proper responses. 1. Create the exception class public class OrderNotFoundException : Exception { public int OrderId { get; } public OrderNotFoundException(int orderId) : base($"Order {orderId} was not found.") => OrderId = orderId; public OrderNotFoundException(int orderId, Exception innerException) : base($"Order {orderId} was not found.", innerException) => OrderId = orderId; } Guidelines - Inherit from Exception (not ApplicationException, which is no longer recommended). - Name it with the Exception suffix. - Provide constructors for a message and an inner exception, plus useful properties (OrderId) for logging and handling. - In modern .NET, binary serialization constructors and [Serializable] are not needed (BinaryFormatter is obsolete). 2. A base type for domain errors (optional but useful) public abstract class DomainException(string message, string code) : Exception(message) { public string Code { get; } = code; } public sealed class InsufficientStockException(string sku, int requested, int available) : DomainException($"Only {available} units of {sku} are available; {requested} requested.", "insufficient_stock"); 3. Throw it where the rule is violated var order = await _db.Orders.FindAsync([id], ct) ?? throw new OrderNotFoundException(id); if (product.Stock < quantity) throw new InsufficientStockException(product.Sku, quantity, product.Stock); 4. Handle it centrally (ASP.NET Core, .NET 8+) public sealed class DomainExceptionHandler(IProblemDetailsService problems) : IExceptionHandler { public async ValueTask<bool> TryHandleAsync(HttpContext ctx, Exception ex, CancellationToken ct) { int? status = ex switch { OrderNotFoundException => StatusCodes.Status404NotFound, InsufficientStockException => StatusCodes.Status409Conflict, _ => null }; if (status is null) return false; // let other handlers deal with it ctx.Response.StatusCode = status.Value; return await problems.TryWriteAsync(new() { HttpContext = ctx, Exception = ex, ProblemDetails = { Status = status, Title = ex.Message, Extensions = { ["code"] = (ex as DomainException)?.Code } } }); } } builder.Services.AddProblemDetails(); builder.Services.AddExceptionHandler<DomainExceptionHandler>(); app.UseExceptionHandler(); Best practices - Use custom exceptions for exceptional or rule-violation situations, not for normal control flow; for expected outcomes, consider returning results (a Result pattern or TryXxx methods). - Keep messages safe to show to users, or map them to user-friendly messages; never include sensitive data. - Preserve the original exception as the inner exception when wrapping. - Do not create a separate exception type for every tiny case — create them when callers need to handle them differently.
Ravindra Wadile · · 0 likes