6 Data validation and error handling

 

This chapter covers

  • Overview of model binding and data validation
  • Built-in and custom validation attributes
  • ModelState validation approaches
  • Error and exception handling techniques

For simplicity, up to this point we’ve assumed that the data coming from clients is always correct and adequate for our web API’s endpoints. Unfortunately, this is not always the case: whether we like it or not, we often have to deal with erroneous HTTP requests, which can be caused by several factors (including malicious attacks) but always occur because our application is facing unexpected or unhandled behavior.

In this chapter, we’ll discuss a series of techniques for handling unexpected scenarios during the client-server interaction. These techniques rely on two main concepts:

  • Data validation—A set of methods, checks, routines, and rules to ensure that the data coming into our system is meaningful, accurate, and secure and therefore is allowed to be processed
  • Error handling—The process of anticipating, detecting, classifying, and managing application errors that might happen within the program execution flow

In the upcoming sections, we’ll see how we can put them into practice within our code.

6.1 Data validation

6.1.1 Model binding

6.1.2 Data validation attributes

6.1.3 A nontrivial validation example

6.1.4 Data validation and OpenAPI

6.1.5 Binding complex types

6.2 Error handling

6.2.1 The ModelState object

6.2.2 Custom error messages

6.2.3 Manual model validation

6.2.4 Exception handling

6.3 Exercises