Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7502759
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T20:58:53+00:00 2026-05-29T20:58:53+00:00

How can I pass custom error information from an ASP.NET MVC3 JsonResult method to

  • 0

How can I pass custom error information from an ASP.NET MVC3 JsonResult method to the error (or success or complete, if need be) function of jQuery.ajax()? Ideally I’d like to be able to:

  • Still throw the error on the server (this is used for logging)
  • Retrieve custom information about the error on the client

Here is a basic version of my code:

Controller JsonResult method

public JsonResult DoStuff(string argString)
{
    string errorInfo = "";

    try
    {
        DoOtherStuff(argString);
    }
    catch(Exception e)
    {
        errorInfo = "Failed to call DoOtherStuff()";
        //Edit HTTP Response here to include 'errorInfo' ?
        throw e;
    }

    return Json(true);
}

JavaScript

$.ajax({
    type: "POST",
    url: "../MyController/DoStuff",
    data: {argString: "arg string"},
    dataType: "json",
    traditional: true,
    success: function(data, statusCode, xhr){
        if (data === true)
            //Success handling
        else
            //Error handling here? But error still needs to be thrown on server...
    },
    error: function(xhr, errorType, exception) {
        //Here 'exception' is 'Internal Server Error'
        //Haven't had luck editing the Response on the server to pass something here
    }
});

Things I’ve tried (that didn’t work out):

  • Returning error info from catch block
    • This works, but the exception can’t be thrown
  • Editing HTTP response in catch block
    • Then inspected xhr in the jQuery error handler
    • xhr.getResponseHeader(), etc. contained the default ASP.NET error page, but none of my information
    • I think this may be possible, but I just did it wrong?
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T20:58:55+00:00Added an answer on May 29, 2026 at 8:58 pm

    You could write a custom error filter:

    public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.StatusCode = 500;
                filterContext.ExceptionHandled = true;
                filterContext.Result = new JsonResult
                {
                    Data = new
                    {
                        // obviously here you could include whatever information you want about the exception
                        // for example if you have some custom exceptions you could test
                        // the type of the actual exception and extract additional data
                        // For the sake of simplicity let's suppose that we want to
                        // send only the exception message to the client
                        errorMessage = filterContext.Exception.Message
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
        }
    }
    

    and then register it either as a global filter or only apply to particular controllers/actions that you intend to invoke with AJAX.

    And on the client:

    $.ajax({
        type: "POST",
        url: "@Url.Action("DoStuff", "My")",
        data: { argString: "arg string" },
        dataType: "json",
        traditional: true,
        success: function(data) {
            //Success handling
        },
        error: function(xhr) {
            try {
                // a try/catch is recommended as the error handler
                // could occur in many events and there might not be
                // a JSON response from the server
                var json = $.parseJSON(xhr.responseText);
                alert(json.errorMessage);
            } catch(e) { 
                alert('something bad happened');
            }
        }
    });
    

    Obviously you could be quickly bored to write repetitive error handling code for each AJAX request so it would be better to write it once for all AJAX requests on your page:

    $(document).ajaxError(function (evt, xhr) {
        try {
            var json = $.parseJSON(xhr.responseText);
            alert(json.errorMessage);
        } catch (e) { 
            alert('something bad happened');
        }
    });
    

    and then:

    $.ajax({
        type: "POST",
        url: "@Url.Action("DoStuff", "My")",
        data: { argString: "arg string" },
        dataType: "json",
        traditional: true,
        success: function(data) {
            //Success handling
        }
    });
    

    Another possibility is to adapt a global exception handler I presented so that inside the ErrorController you check if it was an AJAX request and simply return the exception details as JSON.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

how can i pass values from my custom components back to the main.mxml? i
How can I pass some data from a Global.asax event handler to a custom
You can pass a function pointer, function object (or boost lambda) to std::sort to
You can pass special strings into jQuery's Datepicker class setDate() method like +7 which
I know you can pass arguments through the RunWorkerAsync function call when you first
I know from here that I can pass an ignore option in the jQuery.validate
I have an Asp.Net repeater, which contains a textbox and a checkbox. I need
how can one use a Safearray to pass an array of custom types (a
I implement a ASP.NET MVC3 application, where data is accessed through WCF services. The
Using logparser you can pass on parameters to the query you'd like to run

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.