Skip to main content

Lesson 7 of 9

Exception Handling - Result Pattern & ProblemDetails

In production backends, exceptions should NOT be used for expected business outcomes (not found, validation failure). The Result<T> pattern makes error paths explicit and forces callers to handle them. ProblemDetails (RFC 7807) is the industry standard for API error responses.

20 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Result<T> Pattern

Result<T> Pattern
// ━━ Result<T> - explicit error handling without exceptions ━━
public record Result<T>
{
    public bool IsSuccess { get; }
    public T? Value { get; }
    public string? ErrorMessage { get; }
    public ErrorType? ErrorType { get; }

    private Result(bool isSuccess, T? value, string? error, ErrorType? type) =>
        (IsSuccess, Value, ErrorMessage, ErrorType) = (isSuccess, value, error, type);

    public static Result<T> Success(T value) => new(true, value, null, null);
    public static Result<T> NotFound(string msg) => new(false, default, msg, Models.ErrorType.NotFound);
    public static Result<T> Conflict(string msg) => new(false, default, msg, Models.ErrorType.Conflict);
    public static Result<T> Validation(string msg) => new(false, default, msg, Models.ErrorType.Validation);
}

public enum ErrorType { NotFound, Validation, Conflict, Unauthorized, ServerError }

// ━━ Service returns Result instead of throwing ━━
public async Task<Result<Product>> CreateProductAsync(CreateProductRequest request, CancellationToken ct)
{
    var exists = await repository.ExistsByNameAsync(request.Name, ct);
    if (exists)
        return Result<Product>.Conflict($"Product '{request.Name}' already exists");

    if (request.Price <= 0)
        return Result<Product>.Validation("Price must be greater than zero");

    var product = new Product { Id = Guid.NewGuid().ToString(), Name = request.Name, Price = request.Price, IsActive = true, CategoryId = "" };
    await repository.AddAsync(product, ct);
    return Result<Product>.Success(product);
}

// ━━ Controller maps Result to HTTP - no try/catch needed ━━
[HttpPost]
public async Task<IActionResult> CreateProduct(
    [FromBody] CreateProductRequest request, CancellationToken ct)
{
    var result = await _service.CreateProductAsync(request, ct);

    return result switch
    {
        { IsSuccess: true, Value: var product } => CreatedAtAction(nameof(GetProduct), new { id = product!.Id }, product),
        { ErrorType: ErrorType.Conflict }  => Conflict(new ProblemDetails { Title = "Conflict", Detail = result.ErrorMessage, Status = 409 }),
        { ErrorType: ErrorType.Validation } => UnprocessableEntity(new ProblemDetails { Title = "Validation Error", Detail = result.ErrorMessage, Status = 422 }),
        _ => StatusCode(500)
    };
}

record CreateProductRequest(string Name, decimal Price);
class Product { public string Id { get; set; } = ""; public string Name { get; set; } = ""; public decimal Price { get; set; }  public bool IsActive { get; set; } public string CategoryId { get; set; } = ""; }
interface IRepository { Task<bool> ExistsByNameAsync(string name, CancellationToken ct); Task AddAsync(Product p, CancellationToken ct); }
IRepository repository = null!;
Task<IActionResult> GetProduct(object id) => Task.FromResult<IActionResult>(new Microsoft.AspNetCore.Mvc.OkResult());
class _service { public static Task<Result<Product>> CreateProductAsync(CreateProductRequest r, CancellationToken ct) => Task.FromResult(Result<Product>.Success(new Product())); }

Tip

Tip

Practice Exception Handling Result Pattern ProblemDetails in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Exception Handling Result Pattern ProblemDetails from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Exception Handling Result Pattern ProblemDetails is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/9 done