TaskHub.Shared

Domain Exceptions & Errors

TaskHub.Shared.Domain uses a structured approach to handling business logic errors, distinguishing them from infrastructure or technical exceptions.

DomainErrorBase

Instead of using plain strings for error messages, we use DomainErrorBase (a record) to encapsulate error metadata.

public abstract record DomainErrorBase(int Code, string Domain, string Description);

Standardizing Errors

Applications should define their domain errors as static members:

public static class ProjectErrors
{
    public static readonly DomainErrorBase InvalidName = 
        new(400, "Project", "Project name cannot be empty.");
        
    public static readonly DomainErrorBase ProjectFull = 
        new(409, "Project", "Project has reached the maximum number of tasks.");
}

DomainException

When a domain invariant is violated, a DomainException is thrown. This exception carries the DomainErrorBase.

public class DomainException(DomainErrorBase errorCode) : Exception(errorCode.Description)
{
    public DomainErrorBase ErrorCode { get; } = errorCode;
}

Why use DomainException?

  1. Rich Metadata: It carries more than just a message; it includes a machine-readable code and a domain identifier.
  2. Global Handling: It can be easily caught by a global exception filter and transformed into a standardized Result with the appropriate ResultCode.
  3. Consistency: Ensures that the same error always results in the same message and code across the entire system.

Best Practices