Angular $http error response statusText always undefined

13,588

Solution 1

For anyone else who may have had this issue, the message was in data.Message. I found it by debugging the JS.

Solution 2

Replace .error() by .catch().

$http.post('/url',json)
    .success(function(data, status, headers, config){

      // some code here

    })
    .catch(function(data, status, headers, config){ // <--- catch instead error

        data.statusText; //contains the error message

    });

Solution 3

StatusText is only available by using the .then from $http, NOT from .Post helper methods and NOT from .success .error.

    function handleSuccess(data, status, headers, config, statusText){
       //some function of your own invention
    }
    function handleError(data, status, headers, config, statusText){
       //some function of your own invention
    }
    //borrowed from angularJs Http module
    function headersGetter(headers) {
        var headersObj = isObject(headers) ? headers : undefined;

        return function(name) {
            if (!headersObj) headersObj =  parseHeaders(headers);

            if (name) {
                var value = headersObj[lowercase(name)];
                if (value === void 0) {
                    value = null;
                }
                return value;
            }

            return headersObj;
        };
    }

    //borrowed from angularJs Http module
    function isSuccess(status) {
        var istatus = Math.max(status, 0);
        return 200 <= istatus && istatus < 300;
    }

    $scope.postMyData = function ($http)
    {
        var req = {
            method: 'POST',
            url: 'destinationURL.html',
            headers: {
                'Content-Type': 'application/json'
            },
            data: $scope,
        };

        // example response from :
        //http://plnkr.co/edit/atRTBQC62YdZzKH8mWqu?p=preview
        //{
        //  "data":"Hello, $http!",
        //  "status":200,
        //  "config":{
        //    "method":"GET",
        //    "transformRequest":[null],
        //    "transformResponse":[null],
        //    "url":"http-hello.html",
        //    "cache":{},
        //    "headers":{"Accept":"application/json, text/plain, */*"}
        //  },
        //    "statusText":"OK"}

        $http(req).
            then(function (response) {
                var data = response.data;
                var status = response.status;
                var headers = headersGetter(headers)
                var config = response.config;
                var statusText = response.statusText;

                scope.messageToUsers = (isSuccess(response.status))
                    ? handleSuccess(data, status, headers, config, statusText)
                    : handleError(data, status, headers, config, statusText);
            })
    }
Share:
13,588
CoolCriSyS
Author by

CoolCriSyS

Updated on June 23, 2022

Comments

  • CoolCriSyS
    CoolCriSyS almost 2 years

    I am trying to return a custom error message to the user to let them know what went wrong if an error occurs, but I have tried everything to display the message and nothing seems to be capturing it. Here is my angular code:

    $scope.save = function (style) {
        styleAPIservice.addStyle(style).success(function () {
            $scope.success = "Style added successfully";
        }).error(function (data, status, headers, config, statusText) {
            $scope.error = "An error occurred while saving style: " + data + "|"+data.data+"|"+data.statusText+"|"+statusText;
        });
    }
    

    Here is the styleAPIservice function it's calling:

    styleAPI.addStyle = function (style) {
        return $http.post(AppRoot + "api/StyleAPI/",
            JSON.stringify(style),
                {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
    }
    

    And here is the API function:

    [HttpPost]
    public HttpResponseMessage PostStyle(Style style)
    {
        if (string.IsNullOrEmpty(style.Pattern.PatternName) || string.IsNullOrEmpty(style.StockNumber))
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Pattern Name and Stock Number are required.");
    
        var checkStyle = StyleRepository.LoadStyleByStockNumber(style.StockNumber);
        if (checkStyle != null)
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Style number already exists. Please use update.");
    
        try
        {
            // Save style
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error creating style: " + ex.Message);
        }
    
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, style);
        response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = style.StyleId }));
        return response;
    }
    

    And here is what is returned when an error occurs (such as Style already exists):

    An error occurred while saving style: [object Object]|undefined|undefined|undefined
    

    What am I doing wrong? I feel like I've searched everywhere and tried every possible suggestion, but I am just at a loss as to why I can't display my error messages.

  • CoolCriSyS
    CoolCriSyS about 9 years
    Good to know. Thanks!