Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

296
Views
Not getting the error message from asp.net web api backend in $ajax method

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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
}
about 4 years ago · Juan Pablo Isaza Report

0

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);
         }
    }
about 4 years ago · Juan Pablo Isaza Report

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!