skip to Main Content

I have a simple ASP.Net Web API method that returns a BadRequest like this ..

catch (Exception ex) 
            {
                Log.Error($"CreateRequest:requestedBy:{requestedBy.FirstName} {requestedBy.Surname} {requestedBy.EmailAddress} Message:{ex.Message} Stack Trace:{ex.ToString()}");
                return BadRequest(ex.Message);
                
            }

The calling front end catches the error the usual way like this..

$.ajax({ 
                url: ResolveUrl(urlPath),
                data: jsonbody,
                type: 'POST',                                
                contentType: "application/json",
                success: function (data) {
                    //do something with data
                },
                error: function (response, textStatus, errorThrown) {                       
                      toastr.error(response.responseJSON || response.statusText);                        
                },
                complete: function (jxXHR, message)
                {
                    //do something here
                }
            });

The issue is the statusText in the response object in the error: method only has "BadRequest" and NOT the actual string that was passed in ex.Message from the back end.

This has worked before no problem and been doing this for years. The text in ex.Message is "asset category missing" but that is nowhere to be seen on the response object in the $.ajax method.

3

Answers


  1. Chosen as BEST ANSWER

    The issue was web.config was overriding the error handling.. thats why i didnt see the original error and saw the html content instead.. it had this which is now commented out.

     <httpErrors errorMode="Custom" existingResponse="Replace"> 
          <clear />
          <remove statusCode="400" />
          <remove statusCode="401" />
          <remove statusCode="404" />
          <remove statusCode="500" />
          <error statusCode="400" path="500.html" responseMode="File" />
          <error statusCode="401" path="500.html" responseMode="File" />
          <error statusCode="404" path="404.html" responseMode="File" />
          <error statusCode="500" path="500.html" responseMode="File" />
        </httpErrors>
    

  2. I use on error this way

    error: function (jqXHR, exception) {
    var status =jqXHR.status; //400
    var message = jqXHR.responseText;
    var ex= exception; // 'abort' for example
    
    ....your code
    }
    
    Login or Signup to reply.
  3. https://dotnetfiddle.net/HwxlOF
    I do this. By the way use success for ajax to show exceptions.

    View:

    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
        <script>
    
            $(function () {
                $("#theBtn").click(function () {
                    alert("in the click...");
                    $.ajax({
                        type: "GET",
                        url: "/api/values",  //I changed this url
                        async: false,
                        cache: false,
                        dataType: "json",
                        contentType: "application/json",
                        success: function (jsn) {
                            alert(jsn);
                        },
                        error: function (error) {
                            alert("error");
                            console.log(error);
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <div>
            <input type="button" id="theBtn" value="Click to start ajax" />
        </div>
    </body>
    </html>
    

    API:

    public class ValuesController : ApiController
    {
        public HttpResponseMessage Get()
        {
            try
            {
                throw new Exception("Luke Perrin shows exception");
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.OK, ex.Message);
             }
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search