Is there a way to get HTTP status code name using JS and AngularJS?
Asked Answered
Z

5

5

I have an AngularJS, JS, JQ, HTML5, CSS3 web app. It is suposed to send different HTTP methods to REST API of our projects and manipulate them. It has similar behavior to DHC by Restlet (formerly Dev HTTP Client). Every request returns a status code like 200, 201, 404, 500 etc. which is then displayed to the user.

Now what I would like is to display not only a response code, but also a description of it like this:

404 Not Found, 201 Created etc.

I am getting a response from Angular like this:

$http(config).success(function (data, status, headers, config) {//some logic}

Does anyone know if this is possible using AngularJS?

Zigzag answered 10/4, 2014 at 11:58 Comment(0)
Y
0

If I'm not wrong, you can still use jQuery ajax for your call, and setup your response with $.ajaxSetup like this:

$.ajaxSetup({
    type: "GET",
    dataType: "jsonp",
    error: function(xhr, exception){
        if( xhr.status === 0)
            alert('Error : ' + xhr.status + 'You are not connected.');
        else if( xhr.status == "201")
            alert('Error : ' + xhr.status + '\nServer error.');
        else if( xhr.status == "404")
            alert('Error : ' + xhr.status + '\nPage note found');
        else if( xhr.status == "500")
             alert('Internal Server Error [500].');
        else if (exception === 'parsererror') 
            alert('Error : ' + xhr.status + '\nImpossible to parse result.');
        else if (exception === 'timeout')
            alert('Error : ' + xhr.status + '\nRequest timeout.');
        else
            alert('Error .\n' + xhr.responseText);
    }
});
Yevetteyew answered 10/4, 2014 at 12:15 Comment(4)
I can receive a plenty of different response codes. If i'd follow your advice - it'll be a large if-esle statement. It's not the solution I am looking for. By the way, it'd look better with switch-case.Zigzag
What does that mean look better ? It's exactly the same thing, please note that in over language like Java, you can't switch case on string. This is good practice for me when I switch beetwen programming language.Yevetteyew
@ Kopax Jack Herrauer Why wouldn't Java's switch-case work with Strings? That's nonsense. "A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes.." docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.htmlZigzag
@Nazar Sobchuk : I know, but depending of JRE level, I should have say that on my answer "Cannot switch on a value of type String for source level below 1.7. Only convertible int or enum constants are permitted"Yevetteyew
Z
12

Well, I ended up with the following solution:

I created a constant variable and listed all HTTP codes and their description (you can copy them to your own program):

constants.js:

var HTTP_STATUS_CODES = {
        'CODE_200' : 'OK',
        'CODE_201' : 'Created',
        'CODE_202' : 'Accepted',
        'CODE_203' : 'Non-Authoritative Information',
        'CODE_204' : 'No Content',
        'CODE_205' : 'Reset Content',
        'CODE_206' : 'Partial Content',
        'CODE_300' : 'Multiple Choices',
        'CODE_301' : 'Moved Permanently',
        'CODE_302' : 'Found',
        'CODE_303' : 'See Other',
        'CODE_304' : 'Not Modified',
        'CODE_305' : 'Use Proxy',
        'CODE_307' : 'Temporary Redirect',
        'CODE_400' : 'Bad Request',
        'CODE_401' : 'Unauthorized',
        'CODE_402' : 'Payment Required',
        'CODE_403' : 'Forbidden',
        'CODE_404' : 'Not Found',
        'CODE_405' : 'Method Not Allowed',
        'CODE_406' : 'Not Acceptable',
        'CODE_407' : 'Proxy Authentication Required',
        'CODE_408' : 'Request Timeout',
        'CODE_409' : 'Conflict',
        'CODE_410' : 'Gone',
        'CODE_411' : 'Length Required',
        'CODE_412' : 'Precondition Failed',
        'CODE_413' : 'Request Entity Too Large',
        'CODE_414' : 'Request-URI Too Long',
        'CODE_415' : 'Unsupported Media Type',
        'CODE_416' : 'Requested Range Not Satisfiable',
        'CODE_417' : 'Expectation Failed',
        'CODE_500' : 'Internal Server Error',
        'CODE_501' : 'Not Implemented',
        'CODE_502' : 'Bad Gateway',
        'CODE_503' : 'Service Unavailable',
        'CODE_504' : 'Gateway Timeout',
        'CODE_505' : 'HTTP Version Not Supported'
    };

And then in my AngularJS controller, when I receive a status from $http I just call this function, which set's the value of status code message to a model:

setResponseCodeDescr = function(responseCode) {

var responseCodeConstant = 'CODE_'.concat(responseCode);

if (HTTP_STATUS_CODES[responseCodeConstant]){
    $rootScope.response.description = HTTP_STATUS_CODES[responseCodeConstant];
} else {
    $rootScope.response.description = "";
}

}

That's all :)

Zigzag answered 10/4, 2014 at 13:44 Comment(1)
For some value of "all".Willie
M
2

When making the call with Angular, you get the status code back, with the status variable you showed in your success function. Angular does not seem to return the text to go with it to you, in any way I have seen.

You could do it with a switch statement to display the message to go with the code, but obviously the can be a long switch statement for all possible codes. You also could return the message you want to display as part of the data, which is nothing more than putting the work around on your backend instead of the front end.

As far as doing the translation from code to message, I would suggest placing it in a directive (or filter) and reuse that across your app to take a code and return the message to go with it to show in the UI.

Marindamarinduque answered 10/4, 2014 at 13:16 Comment(0)
P
1

I'd make as suggested by "amenoire/Jason C", but the constants

var HTTP_STATUS_CODES = {
        '200' : 'OK',
        '201' : 'Created'
...
        '505' : 'HTTP Version Not Supported'
};

wrote without prefix "CODE_" and call them as

var s =  HTTP_STATUS_CODES[xmlhttp.status]
if (!(s && s.length > 0)) s = 'look at https://developer.mozilla.org/en-US/docs/Web/HTTP/Status'
Patras answered 5/3, 2017 at 12:40 Comment(1)
Well, yeah. I thought of it at that time as well, but the reason I did prefer the constant values was the fact that this will perform an additional request to the site and taking into account that the network connection might be poor, the site might be unreachable, I thought that this particular solution would bring more troubles than the constants approach. Also these codes are not something that tend to change, they're pretty static :) Maybe there's no such problem in Angular anymore and you're able to get those directly from the response.Zigzag
Y
0

If I'm not wrong, you can still use jQuery ajax for your call, and setup your response with $.ajaxSetup like this:

$.ajaxSetup({
    type: "GET",
    dataType: "jsonp",
    error: function(xhr, exception){
        if( xhr.status === 0)
            alert('Error : ' + xhr.status + 'You are not connected.');
        else if( xhr.status == "201")
            alert('Error : ' + xhr.status + '\nServer error.');
        else if( xhr.status == "404")
            alert('Error : ' + xhr.status + '\nPage note found');
        else if( xhr.status == "500")
             alert('Internal Server Error [500].');
        else if (exception === 'parsererror') 
            alert('Error : ' + xhr.status + '\nImpossible to parse result.');
        else if (exception === 'timeout')
            alert('Error : ' + xhr.status + '\nRequest timeout.');
        else
            alert('Error .\n' + xhr.responseText);
    }
});
Yevetteyew answered 10/4, 2014 at 12:15 Comment(4)
I can receive a plenty of different response codes. If i'd follow your advice - it'll be a large if-esle statement. It's not the solution I am looking for. By the way, it'd look better with switch-case.Zigzag
What does that mean look better ? It's exactly the same thing, please note that in over language like Java, you can't switch case on string. This is good practice for me when I switch beetwen programming language.Yevetteyew
@ Kopax Jack Herrauer Why wouldn't Java's switch-case work with Strings? That's nonsense. "A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes.." docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.htmlZigzag
@Nazar Sobchuk : I know, but depending of JRE level, I should have say that on my answer "Cannot switch on a value of type String for source level below 1.7. Only convertible int or enum constants are permitted"Yevetteyew
N
0

Getting the code technically, seems easy though, "just attaching the inbuilt properties of the response will get you the description".

It's explained in the docs actually, once you have the response along with its properties, you can do anything with it. And the other way is creating a CONSTANT, but I don't think we usually need so much.

$http({
    method: 'GET',
    url: '/someUrl'
}).then(function successCallback(response) {
    var status = response.status;
    console.log(status); // gives the status 200/401
    var statusText = response. statusText;
    console.log(status); // HTTP status text of the response
}, function errorCallback(response) {

});
Neoplasm answered 23/10, 2015 at 0:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.