Visit Mozilla.org

Components.isSuccessCode

From MDC


Contents

[edit] Summary

Determines whether a given XPCOM return code indicates the success or failure of an operation, returning true or false respectively.

[edit] Syntax

var succeeded = Components.isSuccessCode(returnCode);

[edit] Parameters

returnCode 
The return code to be checked

[edit] Description

Components.isSuccessCode() may be used to determine whether an XPCOM return code 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.

Note: A non-zero XPCOM return code (i.e., not 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's onStopRequest method). To determine the success or failure of the complex task, you would call Components.isSuccessCode() upon the status code included in the notification.

[edit] Examples

[edit] 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():

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);
  copier.asyncCopy(copyObserver, null);
}