Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return error from ASP.NET MVC action

I am using ASP.NET MVC for developing a web site. I am using jquery for AJAX functionality. In the action methods, I want to return some error to signal that the input is not correct or that the action could not be performed. In such error cases, I expect the jquery ajax error handler to be called and I can take appropriate action in there. I have not found a way how to do this. Following is my action method.

In error cases, what should I be sending from an Action in order to get the jquery error handler triggered?

public ActionResult AddToFavourites(int entityId, string entityType)
    {

        if (!Request.IsAjaxRequest())
            throw new InvalidOperationException("This action can be called only in async style.");

        try
        {
            RBParams.EntityType typeOfFavourite = (RBParams.EntityType)Enum.Parse(typeof(RBParams.EntityType), entityType);
            string status = "";

            if (typeOfFavourite == RBParams.EntityType.BusinessEntity)
            {
                status = MarkFavouriteEntity(entityId);
            }
            else if (typeOfFavourite == RBParams.EntityType.Review)
            {
                status = MarkFavouriteReview(entityId);
            }
            else
            {
                throw new InvalidOperationException("The type of the entity is not proper");
            }

            return Content(status);

        }
        catch (Exception ex)
        {

            return Content("Error");
        }
    }
like image 852
dotcoder Avatar asked Mar 04 '10 09:03

dotcoder


People also ask

How do I return an error in Actionresult?

You should be logging the relevant information to your error log so that you can go through it and fix the issue. If you want to show the error in the form user submitted, You may use ModelState. AddModelError method along with the Html helper methods like Html.

How do you return a message in controller?

We can return the custom message from controller by throwing exception and handling it at client side using the ActionFailure event of the Grid. Grid Rendering Code. 2. Handle the returned message in the ActionFailure event of the Grid.


1 Answers

Your ajax error handler will be called when the action doesn't return a expected status code. It will, for example, fire if the action wasn't found or if you throw a exception that you don't handle. In your case it will be called if you don't catch the error in your action (as the action will return a 500 status code).

I would, however, not do it in this way as this is probably a expected error. I would rather return json both when you succeed and when you have a error. Then you can indicate if it is a successful call or not. Something like this:

public ActionResult AddToFavourites(int entityId, string entityType)
{

    if (!Request.IsAjaxRequest())
        throw new InvalidOperationException("This action can be called only in async style.");

    try
    {
        RBParams.EntityType typeOfFavourite = (RBParams.EntityType)Enum.Parse(typeof(RBParams.EntityType), entityType);
        string status = "";

        if (typeOfFavourite == RBParams.EntityType.BusinessEntity)
        {
            status = MarkFavouriteEntity(entityId);
        }
        else if (typeOfFavourite == RBParams.EntityType.Review)
        {
            status = MarkFavouriteReview(entityId);
        }
        else
        {
            throw new InvalidOperationException("The type of the entity is not proper");
        }

        return Json(new { Success = true, Status = status });

    }
    catch (Exception ex)
    {

        return Json(new { Success = false, Message = ex.Message });
    }
}

Then you handle it in the same way as a successful call. You just check the Success property of your json response. Then you handle unexpected errors in the error callback.

like image 130
Mattias Jakobsson Avatar answered Oct 09 '22 11:10

Mattias Jakobsson