How to report error to $.ajax without throwing exception in MVC controller?

Akash Kava picture Akash Kava · Jan 2, 2012 · Viewed 56.6k times · Source

I have a controller, and a method as defined...

[HttpPost]
public ActionResult UpdateUser(UserInformation model){

   // Instead of throwing exception
   throw new InvalidOperationException("Something went wrong");


   // I need something like 
   return ExecutionError("Error Message");

   // which should be received as an error to my 
   // $.ajax at client side...

}

Problems with Exceptions

  1. We have to log exceptions in case of device or network errors like SQL Connectivity errors.
  2. These messages are like validation messages for users, we dont want to log.
  3. Throwing exceptions also floods Event Viewer.

I need some easy way to report some custom http status to my $.ajax call so that it should result an error at client side, but I do not want to throw an error.

UPDATE

I cannot change client script because it becomes inconsistent with other data source.

So far, HttpStatusCodeResult should work but it's IIS that is causing the problem here. No matter what error message I set, tried all answers, still I receive default message only.

Answer

Dennis Traub picture Dennis Traub · Jan 2, 2012

This is where HTTP status codes come into play. With Ajax you will be able to handle them accordingly.

[HttpPost]
public ActionResult UpdateUser(UserInformation model){
    if (!UserIsAuthorized())
        return new HttpStatusCodeResult(401, "Custom Error Message 1"); // Unauthorized
    if (!model.IsValid)
        return new HttpStatusCodeResult(400, "Custom Error Message 2"); // Bad Request
    // etc.
}

Here's a list of the defined status codes.