Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

297
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda