Components.isSuccessCode 编辑
Summary
Determines whether a given XPCOM return code (that is, an nsresult
value) indicates the success or failure of an operation, returning true
or false
respectively.
Syntax
var succeeded = Components.isSuccessCode(returnCode);
Parameters
returnCode
- The return code (of type
nsresult
) to be checked.
Description
Components.isSuccessCode()
may be used to determine whether an XPCOM return code (an nsresult
) indicates success or failure. An XPCOM return code indicates success if its high-order bit is 0, and it indicates failure if its high-order bit is 1.
NS_OK
) does not necessarily indicate failure.Components.isSuccessCode()
is functionally equivalent to the following JavaScript:
function isSuccessCode(returnCode) {
return (returnCode & 0x80000000) === 0;
}
Since failure error codes are turned into exceptions when encountered in JavaScript, this function usually is not necessary. However, if you are using asynchronous APIs, it may be essential. For example, if you ask a component or service to asynchronously perform some task, you must usually pass in an object which will be notified when the task is completed. If the task is sufficiently complex that it can fail, the notification will include a status code indicating the success or failure of the operation (see, for example, nsIRequestObserver.onStopRequest()
). To determine the success or failure of the complex task, you would call Components.isSuccessCode()
upon the status code included in the notification.
Examples
Checking whether copying a stream's data succeeded
The following example demonstrates copying data from a buffered nsIInputStream
to an nsIOutputStream
, checking for whether the copy succeeded using Components.isSuccessCode()
.
nsIAsyncStreamCopier.init()
has changed in Gecko 1.9.2, omit last 2 boolean parameters if you're using Gecko 1.9.1 and earlier.const Cc = Components.classes; const Ci = Components.interfaces; const Cr = Components.results; // global flags polled externally var copyFailed = false; var copyInProgress = false; function copyBufferedStream(inStream, outStream) { var copyObserver = { onStartRequest: function(request, context) { copyInProgress = true; }, onStopRequest: function(request, context, statusCode) { copyInProgress = false; // did the copy fail? if (!Components.isSuccessCode(statusCode)) copyFailed = true; }, QueryInterface: function(aIID) { if (aIID.equals(Ci.nsIRequestObserver) || aIID.equals(Ci.nsISupports)) return this; throw Cr.NS_ERROR_NO_INTERFACE; } }; var copier = Cc["@mozilla.org/network/async-stream-copier;1"] .createInstance(Ci.nsIAsyncStreamCopier); copier.init(inStream, outStream, null, true, false, 8192, true, true); copier.asyncCopy(copyObserver, null); }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论