Home > Software engineering >  Not getting the error message from asp.net web api backend in $ajax method
Not getting the error message from asp.net web api backend in $ajax method

Time:03-04

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.

CodePudding user response:

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
}

CodePudding user response:

https://dotnetfiddle.net/ARdtvr 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);
         }
    }
  • Related