Skip to content
This repository was archived by the owner on May 4, 2026. It is now read-only.

Exceptions and CQRS

Tijl Leenders edited this page Jan 5, 2019 · 1 revision

Exceptions

Only used for 'exceptional' situations:

  • Bugs
  • Violation of public contracts
  • NOT FOR FLOW OF CONTROL!

Anything that you can reasonably expect to go wrong should not be handled via exceptions. Instead, use a result object. This does not violating CQS principle (Command Query Separation / Single Responsibility principle) but instead improves upon it.

In short, you should use a result object (not exceptions) if you expect a method:

  • to return null results instead of n objects
  • to return void (command with side-effects) - but these side-effects could fail

CQRS

On CQRS (Command Query Responsibility Segregation) vs CQS (Command Query Separation):

CQRS is used in this project.

CQRS extends CQS to the architectural level:

  • Commands use the domain model to modify data
  • Queries from user interface (ie for a viewmodel) bypass the domain model and query the database directly.

Examples of CQRS are ElasticSearch and database views. CQRS can be done on all the way to the database (making one database for commands and one/multiple for queries), or partly. Most often, the cost/benefit is optimal when separating the API level and the DOMAIN, but keeping a single database/datasource - as syncronising data from command-database/source to read-database/source introduces complexity and risks of presenting/using stale data.

Advantages of CQRS are:

  • Simplicity (domain model doesn't have conflicting concerns for queries/commands)
  • Better scalability (most operations will be reads, so read-database/source can scaled vertically and horizontally independent of command-database/source)
  • Performance (read queries can be optimized (ie flattened and indexed) on the database level without regard for domain model entity structure, or the (often normalized) command-database/source)

Clone this wiki locally