Extra module 2 - Exception Filters

A mechanism to filter and handle exceptions.

Our system is becoming quite interesting! There is a matter to which we did not pay much attention yet, and we shall do so now. Notice that, in some cases, we throw an exception. For example, when an entity is searched for in the database, if it is not found, then TypeORM's repository returns null. We then check if that's the case in order to throw the appropriate exception. However, note that we repeat this pattern throughout the entire system, duplicating code. Due to this, we'll learn in this module a way to isolate this logic into a resource that is more appropriate for this purpose: the Exception Filter.

We'll also deal with cases related to database errors. When dealing with the database, many types of error can occur. Some of them are more common and expected to happen than others, our focus will be on three of them:

  • A value that already exists was assigned to an entity's unique field

  • An entity was associated with another through a non-existing id

  • An entity was deleted but there are entities related to it through a NOT NULL column

Currently, if any of the three aforementioned cases happen, an Internal Server Error is thrown, which is equivalent to a generic error. However, unbeknownst to us, a descriptive error message is generated by the database, even though it is not sent with this default error. We'll then also extract data from these messages using regexes, as this information is not readily available to us in specific fields.

With all this said, let's then get started.

Last updated