Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $http(...) errorHandler receives empty string for data

I have a simple AngularJS $http block like so;

$http(req).then(function successCallback(response) {
    alert(response);
}, function errorCallback(response) {
    alert(response);
});

My issue is that when my ASP.NET Controller returns a HTTP error code, the JS errorCallback receives an object like;

{data: "", status: 304, config: Object, statusText: "Not Modified"}

No matter what I do, I can't seem to populate the data property in my callback.

If instead my controller returns a HTTP OK code, then the 'success' callback is invoked, and the return data is available. But not when it's an error... help!

The controller function is a WebAPI POST handler and looks like;

[System.Web.Http.HttpPost]
public async Task<HttpResponseMessage> Save([FromBody]object data)
{
    ...<snip>...

    return new HttpResponseMessage
    {
        StatusCode = HttpStatusCode.NotModified,
        Content = new JsonContent(JObject.FromObject(new
        {
            success = false,
            message = "User not authorised to perform this action."
        }))
    };
}

The same construct, but with;

StatusCode = HttpStatusCode.OK

Is successfully received in the success callback in the JS.

like image 281
RJ Lohan Avatar asked Oct 30 '22 04:10

RJ Lohan


1 Answers

So after reviewing comments on my question, it turns out that the problem was caused by my selection of Http status codes. I was returning

StatusCode = HttpStatusCode.NotModified,

This code has a special meaning, and it seems the 'data' blob is intentionally stripped.

Instead, if I use a code like

StatusCode = HttpStatusCode.Unauthorized,

The 'data' blob is populated as expected in the Angular callback.

This sample returns the expected error data;

[System.Web.Http.HttpPost]
public async Task<HttpResponseMessage> Save([FromBody]object data)
{
    ...<snip>...

    return new HttpResponseMessage
    {
        StatusCode = HttpStatusCode.Unauthorized,
        Content = new JsonContent(JObject.FromObject(new
        {
            success = false,
            message = "User not authorised to perform this action."
        }))
    };
}
like image 140
RJ Lohan Avatar answered Nov 11 '22 14:11

RJ Lohan