Handle controller logic errors in an ASP.NET MVC 5 web app

This document suggests an approach for handling controller logic errors in an ASP.NET MVC 5 web app.

 

This document was most recently updated in November 2015.

 

Built-in error handling

Some ActionResult types can return an error result.

e.g. 404, there are others

Always use ModelState.IsValid for POST and PUT handling methods.

 

(more to come)

 

What is the problem?

ModelState.IsValid, but there’s a logic error, or other error condition that’s passed in by (for example) a manager or repository middleware result.

Can manually add a ModelState error, and therefore invalidate ModelState.

Then, can return an error message, and the data that was submitted (edited if you need to).

 

How it works

ModelState.AddModelError(string key, string errorMessage)

To add an error message to the view’s ValidationSummary element:

  • the key will be an empty string
  • then add your own custom error message

To add an error message to one of the “form” view model properties (and therefore to one of the HTML Form elements):

  • the key will be the property’s name
  • then add your own custom error message

 

(more to come)

 

.

.

.

.

.

.

.

.

.

.

.

.

.

.

Advertisements
%d bloggers like this: