简体   繁体   中英

Best practice to detect if service is available

I need to detect if my service is available in the moment.

But, for some reason, I receive success in ajax() function when I try to reach some of the service methods even if the service is turned off.

I get an html page with 404 message as data in the success field.

My best guess is to use typeof(data) and compare it with string type.

But I think there must be a better solution.

Nothing special just $.ajax()

 $.ajax({
            url: '../Services/Service.svc/getItems',
            data: {},
            error: function (error) {

            },
            success: function (data, status, xhr) {

            },
            datatype: "json",
        });

Going with the info you provided.

If you are in control of the service (ie: you built it) then you could make the webserver return a 503 code when the service is unavailable. This is something the webserver should do when your service is down.

If not, then you need to check for the 404 error code instead that you are receiving right now and handle it gracefully in your code.

I'm assuming you are using jQuery for the client since you refer to the ajax() call. Here is a basic example to check the errorcode in the fail callback:

var serviceRequest = $.ajax(...);

serviceRequest.done(function(returnedData) {
    // Service is active and returning data.
});

serviceRequest.fail(function (xhr) {
    if(xhr.status == 404) {
        // handle this.
    }

    if(xhr.status == 503) {
        // handle this.
    }
});

Why you are receiving a 404 and hitting the success callback is something I have never seen before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM