天天看點

為Diigo建立Chrome擴充程式,第2部分

In part 1, we introduced some new concepts, explained how we were going to build the extension and demonstrated the use of the Diigo API. In this part, we'll create most of our helper functions and deal with error handling.

在第1部分中 ,我們介紹了一些新概念,解釋了我們如何建構擴充并示範了Diigo API的用法。 在這一部分中,我們将建立大多數幫助函數并處理錯誤處理。

錯誤處理 (Error handling)

When the API returns a response, it's up to us to cover all edge cases and use it adequately. Relying on the request to succeed every time isn't an option – we need to account for not only the ready-state, but also potential failures.

當API傳回響應時,由我們決定是否涵蓋所有邊緣情況并充分使用它。 每次都不能依靠成功的請求–我們不僅要考慮準備狀态,還要考慮潛在的失敗。

In order to clean up the code somewhat and make

background.js

more concise, I compressed the Base64 object into a minified string. The background.js file as it is now looks like this. You can start from that one if you're following along with the code.

為了清理代碼并使

background.js

更加簡潔,我将Base64對象壓縮為一個縮小的字元串。 現在的background.js檔案如下所示 。 如果要遵循代碼,則可以從該代碼開始。

The

xml.readyState === 4

part checks if the request is complete. Once it's complete, we're free to check for the status code. Only 200 means "success", all others mean something went wrong. Using the list of possible responses, we'll modify our code to produce a human readable description of the error that occurred.

xml.readyState === 4

部分檢查請求是否完成。 完成後,我們可以自由檢查狀态碼。 隻有200表示“成功”,其他所有則表示出了問題。 使用可能的響應清單 ,我們将修改代碼,以産生對發生的錯誤的人類可讀描述。

var possibleErrors = {
    400: 'Bad Request: Some request parameters are invalid or the API rate limit is exceeded.',
    401: 'Not Authorized: Authentication credentials are missing or invalid.',
    403: 'Forbidden: The request has been refused because of the lack of proper permission.',
    404: 'Not Found: Either you\'re requesting an invalid URI or the resource in question doesn\'t exist (e.g. no such user).',
    500: 'Internal Server Error: Something is broken.',
    502: 'Bad Gateway: Diigo is down or being upgraded.',
    503: 'Service Unavailable: The Diigo servers are too busy to server your request. Please try again later.',
    other: 'Unknown error. Something went wrong.'
};

xml.onreadystatechange = function() {
    if (xml.readyState === 4) {
        if (xml.status === 200) {
            console.log(xml.responseText);
        } else {
            if (possibleErrors
 !== undefined) {
                console.error(xml.status + ' ' + possibleErrors



);
            } else {
                console.error(possibleErrors.other);
            }
        }
    }
};
                
In the above code, we define a set of error messages and bind each message to a key corresponding to the status code. We then check if the code matches any of the predefined ones and log it in the console. If the request is successful, we output the responseText.


The above error handling is very basic, and not very end-user friendly. Options to improve it are: an alert box when an error occurs, graying out the extension's icon, deactivating the extension, and more. I'll leave that up to you.


We can also wrap the whole shebang into a function, just so it's neatly encapsulated and the global namespace isn't polluted:

      
var possibleErrors = {
    400: 'Bad Request: Some request parameters are invalid or the API rate limit is exceeded.',
    401: 'Not Authorized: Authentication credentials are missing or invalid.',
    403: 'Forbidden: The request has been refused because of the lack of proper permission.',
    404: 'Not Found: Either you\'re requesting an invalid URI or the resource in question doesn\'t exist (e.g. no such user).',
    500: 'Internal Server Error: Something is broken.',
    502: 'Bad Gateway: Diigo is down or being upgraded.',
    503: 'Service Unavailable: The Diigo servers are too busy to server your request. Please try again later.',
    other: 'Unknown error. Something went wrong.'
};

xml.onreadystatechange = function() {
    if (xml.readyState === 4) {
        if (xml.status === 200) {
            console.log(xml.responseText);
        } else {
            if (possibleErrors                
 !== undefined) {
                console.error(xml.status + ' ' + possibleErrors



);
            } else {
                console.error(possibleErrors.other);
            }
        }
    }
};


In the above code, we define a set of error messages and bind each message to a key corresponding to the status code. We then check if the code matches any of the predefined ones and log it in the console. If the request is successful, we output the responseText.


The above error handling is very basic, and not very end-user friendly. Options to improve it are: an alert box when an error occurs, graying out the extension's icon, deactivating the extension, and more. I'll leave that up to you.


We can also wrap the whole shebang into a function, just so it's neatly encapsulated and the global namespace isn't polluted:

      
翻譯自: https://www.sitepoint.com/creating-chrome-extension-diigo-part-2/