3

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.

2
  • Try debugging in to the code to see what's present in the "data" object ? Commented Aug 1, 2014 at 13:13
  • Well, I took your suggestion and debugged in Visual Studio. The message is in data.Message. I feel dumb now. Wasted so much time on this! >.< Thanks for your suggestion! Commented Aug 1, 2014 at 13:32

3 Answers 3

9

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

    });
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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);
            })
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.