2014-12-12 3 views
0

Я новичок в том, чтобы возиться с Swagger, поэтому я мог бы задаться глупым вопросом. Можно ли каким-либо образом предотвратить сбой сайта, когда он «не может читать из api»?Поймать исключения, брошенные Swagger

Мой сайт работает большую часть времени, но если по какой-то причине api, который не читается (или просто недоступен), просто перестает работать. Он по-прежнему отображает api, которому это удалось достичь, но вся функциональность полностью исчезла, даже не способная расширять строку.

Резюмируя:

Как предотвратить чванство от сбоев, когда один или несколько API, неразборчивое и возвращает что-то вроде этого:

Unable to read api 'XXXX' from path http://example.com/swagger/api-docs/XXXX (server returned undefined)

Ниже моя инициализация Swagger:

function loadSwagger() { 
window.swaggerUi = new SwaggerUi({ 
    url: "/frameworks/swagger/v1/api.json", 
    dom_id: "swagger-ui-container", 
    supportedSubmitMethods: ['get', 'post', 'put', 'delete'], 
    onComplete: function (swaggerApi, swaggerUi) { 
     log("Loaded SwaggerUI"); 

     if (typeof initOAuth == "function") { 

      initOAuth({ 
       clientId: "your-client-id", 
       realm: "your-realms", 
       appName: "your-app-name" 
      }); 

     } 
     $('pre code').each(function (i, e) { 
      hljs.highlightBlock(e); 
     }); 
    }, 
    onFailure: function (data) { 
     log("Unable to Load SwaggerUI"); 
    }, 
    docExpansion: "none", 
    sorter: "alpha" 
}); 

$('#input_apiKey').change(function() { 
    var key = $('#input_apiKey')[0].value; 
    log("key: " + key); 
    if (key && key.trim() != "") { 
     log("added key " + key); 
     window.authorizations.add("api_key", new ApiKeyAuthorization('api_key', key, 'header')); 
    } 
}); 

$('#apiVersionSelectID').change(function() { 
    var sel = $('#apiVersionSelectID').val(); 
    window.swaggerUi.url = sel; 
    $('#input_baseUrl').val(sel); 
    $('#explore').click(); 
}); 

window.swaggerUi.load(); 

};

ответ

0

Я искал какое-либо решение этой проблемы, но не смог найти. Вот быстрый взлом, который я сделал для решения проблемы. Надеюсь, это может помочь кому-то, у кого такая же проблема.

В чванство-client.js Найти ошибку функции: функция (ответ) {

я заменил обратный api_fail с addApiDeclaration сделать это сделать апи с некоторой ограниченной информации, даже если она не сможет. Я отправляю объект фиктивного api json с путём, установленным на «/ неспособный загрузить» + _this.url. Я посылаю дополнительный параметр, который может быть истинным или ложным, где true указывает, что это сбой api.

Старый код:

enter cerror: function (response) { 
     _this.api.resourceCount += 1; 
     return _this.api.fail('Unable to read api \'' + 
     _this.name + '\' from path ' + _this.url + ' (server returned ' +response.statusText + ')'); 
    } 

Новый код

error: function (response) { 
     _this.api.resourceCount += 1;         
     return _this.addApiDeclaration(JSON.parse('{"apis":[{"path":"/unable to load ' + _this.url + '","operations":[{"nickname":"A","method":" "}]}],"models":{}}'), true); 
    } 

Я изменил функцию addApiDeclaration в том же файле, чтобы отобразить другое сообщение для неисправного апи сначала добавлением вторичного параметра к нему называется неудачная, а затем оператор if, который проверяет, не удалось ли true, а затем изменит e имя api для «FAILED TO LOAD RESOURCE» + this.name. Это добавляет текст FAILED TO LOAD RESOURCE перед неудачным api.

Старый код

SwaggerResource.prototype.addApiDeclaration = function (response) { 
    if (typeof response.produces === 'string') 
    this.produces = response.produces; 
    if (typeof response.consumes === 'string') 
    this.consumes = response.consumes; 
    if ((typeof response.basePath === 'string') && response.basePath.replace(/\s/g, '').length > 0) 
    this.basePath = response.basePath.indexOf('http') === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath; 
    this.resourcePath = response.resourcePath; 
    this.addModels(response.models); 
    if (response.apis) { 
    for (var i = 0 ; i < response.apis.length; i++) { 
     var endpoint = response.apis[i]; 
     this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces); 
    } 
    } 
    this.api[this.name] = this; 
    this.ready = true; 
    if(this.api.resourceCount === this.api.expectedResourceCount) 
    this.api.finish(); 
    return this; 
}; 

Новый код

SwaggerResource.prototype.addApiDeclaration = function (response, failed) { 
    if (typeof response.produces === 'string') 
    this.produces = response.produces; 
    if (typeof response.consumes === 'string') 
    this.consumes = response.consumes; 
    if ((typeof response.basePath === 'string') && response.basePath.replace(/\s/g, '').length > 0) 
    this.basePath = response.basePath.indexOf('http') === -1 ? this.getAbsoluteBasePath(response.basePath) : response.basePath; 
    this.resourcePath = response.resourcePath; 
    this.addModels(response.models); 
    if (response.apis) { 
    for (var i = 0 ; i < response.apis.length; i++) { 
     var endpoint = response.apis[i]; 
     this.addOperations(endpoint.path, endpoint.operations, response.consumes, response.produces); 
    } 
    } 
    if (failed == true) { 
     this.name = "FAILED TO LOAD RESOURCE - " + this.name; 
    } 
    this.api[this.name] = this; 
    this.ready = true; 
    if(this.api.resourceCount === this.api.expectedResourceCount) 
    this.api.finish(); 
    return this; 
}; 
Смежные вопросы