[SOLVED] Not getting the error message from asp.net web api backend in $ajax method

Issue

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.

Solution

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>

Answered By – LukePerrin

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *