Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

300
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda