简体   繁体   中英

Retrieving server side error details (c#) from an ajax call

When a ajax call is made by my application I throw an error and wish to capture it at my client side. Which approach will be the best.

My server side code is:

try
{
     ...
}
catch (Exception ex)
{
     throw new HttpException("This is my error", ex);
}

My client side code is:

var url = $(this).attr('href');
var dialog = $('<div style="display:none"></div>').appendTo('body');

dialog.load(url, {}, 
    function (responseText, status, XMLHttpRequest) {

            if (status == "error") {
                alert("Sorry but there was an error: " + XMLHttpRequest.status + " " + XMLHttpRequest.statusText);
                return false;
            }
            ....

At runtime, when debugging, I don't get my error details as you can see on the screenshot below:

在此处输入图片说明

I get a generic error:

status: 500
statusText: Internal Server Error

How can I get the detail I sent : "This is my error" ?

Finally I use this method:

Web.config:

<system.web>
  <customErrors mode="On" defaultRedirect="~/error/Global">
    <error statusCode="404" redirect="~/error/FileNotFound"/>
  </customErrors>
</system.web>

ErrorController:

public class ErrorController : Controller
{
    public ActionResult Global()
    {
        return View("Global", ViewData.Model);
    }
    public ActionResult FileNotFound()
    {
        return View("FileNotFound", ViewData.Model);
    }
}

Don't forget to create 2 specific views.

Finally when I need to throw specific error code & description, I proceed like this:

    public ActionResult MyAction()
    {
        try
        {
            ...
        }
        catch
        {
            ControllerContext.RequestContext.HttpContext.Response.StatusCode = 500;
            ControllerContext.RequestContext.HttpContext.Response.StatusDescription = "My error message here";
            return null;
        }
    }

Then client side I receive such error information.

Do something like this

Server side:

try{
 //to try
}catch(Exception ex)
{
    return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Error :"+ ex.Message);
}

Then the request will return an error 500 to javascript but with your exception message.

You can control the detailed error messages being sent to the clients. By default, the detailed error messages can be viewed only by browsing the site from the server itself.

To display custom error in this way from the server side, you need add the rule in your IIS configuration .

You can read this thread, maybe can help you: HOW TO enable the detailed error messages for the website while browsed from for the client browsers?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM