Skip to content

Exceptions

Appropriate exception types must be used to handle errors that occur in different layers throughout the system. This guide is designed to ensure errors are handled correctly and the system behaves consistently.

Business Layer Exceptions

When an error related to the business flow occurs, a BusinessException must be thrown along with a specific error message. This ensures errors tied to business rules are handled effectively.

Infrastructure Layer Exceptions

When an unexpected situation is encountered in infrastructure components, an exception of type InfrastructureException must be used. This approach ensures low-level errors are handled consistently by higher-level systems.

Entity Framework Example

In cases such as an optimistic concurrency error, an exception can be thrown as follows:

try
{
    await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException ex)
{
    throw new InfrastructureException("OptimisticConcurrency", "Need refresh record", ex);
}

MongoDB Driver Example

In an infrastructure using the Mongo driver, an optimistic concurrency error can be handled as follows:

var result = await ReplaceOneAsync(transaction, newFilter, storeObject);

if (result is { IsAcknowledged: true, ModifiedCount: 0 } && await _context.Contacts.CountDocumentsAsync(filter) > 0)
    optimisticConcurrency.Data.Add("ReplaceOneResult", result);

if (optimisticConcurrency.Data.Count > 0)
    throw optimisticConcurrency;

For lower-level errors, we can make use of the exception classes provided by .NET.

  • InvalidOperationException
  • ArgumentException
  • ArgumentNullException
  • ArgumentOutOfRangeException
  • NotSupportedException
  • FileNotFoundException
  • DirectoryNotFoundException
  • AggregateException

📢 You must never throw the NullReferenceException class. This exception class should only be thrown by the framework.

Configuration Layer Exceptions

When incorrect or conflicting settings are detected in the configuration parameters that determine how the application runs (e.g. environment variables, JSON/INI files), an exception of type ConfigurationException must be thrown. This ensures error conditions unrelated to infrastructure or business logic are handled effectively.