Internet Explorer 5.0 Review, Part IV: Exception Handling, Workaround the HRESULT Problem - | WebReference

Internet Explorer 5.0 Review, Part IV: Exception Handling, Workaround the HRESULT Problem -

Internet Explorer 5.0 Review, Part IV: Exception Handling (7)

Using HRESULT Values in JavaScript

When you call JavaScript functions from within JavaScript code, you are in relatively a good shape. You can create any objects you want and assign their properties as you like. When catching the exception object, you know exactly which numbers you need to check against and handle the exception as you see fit. You can see examples for this try...catch statements in previous pages of this column.

Things get stickier when you call some foreign components. Luckily for all of us, the Window operating system supports the COM standard, which defines how software modules should communicate between themselves during run-time. This COM standard, among other requirements, defines the return values that COM components should return upon a successful completion or an early exception. You can find these different return values documented under Visual Basic Err.Number error values. You won't be surprised to read that JavaScript's Error.number values are the same as Err.Number ones. The problem is that the documentation for some COM components provides the error values in a hexadecimal format. This is not surprising because HRESULT, the primary standard according to which COM methods communicates return information to their caller, is based on a hexadecimal notation. HRESULT is a 32-bit value and is divided into several fields. Each field may have several possible values according to the error type and nature.

The difficulty with hexadecimal notation is twofold. First, JavaScript does not handle hexadecimal comparisons very well. Second, the high bit in HRESULT is always set, so conversion to based-10 number is not that trivial. Suppose your try...catch statement looks like that:

try {
  // call a COM object 
catch (exception) {
  // check if exception if of Error object type
  if ((exception instanceof Error) &&
      (exception.number == 0x80032D33)) {
    // handle the error from objectiveGrid
    alert("An error in Objective Grid, call the vendor");
  // otherwise throw the exception to the caller/browser
  else throw exception;

The comparison exception.number == 0x80032D33 would not work in JavaScript due to a bug in sign-extension of numbers. To work around this bug, you need to convert the comparison to a signed base-10 one. The recipe for converting signed hexadecimal numbers to signed 10-based ones is the following:

In summary, your comparison above should look like this:

 if ((exception instanceof Error) &&
      (exception.number == -2147275469))

Produced by Yehuda Shiran and Tomer Shiran

Created: April 26, 1999
Revised: April 26, 1999