This video is available to students only

Working on Validation Error Response

In this lesson, we're going to format our validation error response

Validation error response#

We're almost done shaping our errors. We are just left with this validation error. As you can see, it has an additional errors object which carries the key value pairs of the property and the error message. This can obviously be more than one, and will be generated when there is some property which is received empty or is in an incorrect format. What we want to do is include an errors property which will simply send the error messages in an array rather than as objects. Let's see how to do it.

Inside ErrorResponse folder, let's create a new class called ApiValidationErrorResponse. This will derive from our ApiResponse as well. Let's create a constructor; we are not going to set anything while initializing it, we just know that the status code will be 400 for validation error. So inside base, we can write 400. Since we are going to send an array of string as response, we can create a new property which will be public IEnumerable of string, and we can simply call it Errors.


Our APIController is responsible for showing us the error in this format. To tweak the error response, we will have to override the behaviour of our Api Controller. For this, we'll have to go to our startup class. Here, it's important to keep it below the services.AddControllers, so we can write services.Configure. Inside angled brackets, we will mention the type of service which is ApiBehaviorOptions; inside this, we can tweak this with options.

Start a new discussion. All notification go to the author.