Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate COM error codes in C#

In C, Pascal, and C++ it is possible to use the FormatMessage function to retrieve a "friendly" error message that corresponds to a COM HRESULT error code. This question contains sample code that demonstrates the C++ approach. Of course it would be possible to build a managed C++ assembly to perform this function for C# and VB.NET code, but I'm wondering: is there a way to translate COM error codes using the .NET system libraries?

like image 554
Paul Keister Avatar asked Jan 07 '11 00:01

Paul Keister


People also ask

What is error code in C?

Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code errno. It is set as a global variable and indicates an error occurred during any function call.

Should error messages be translated?

Depends on the app. A highly technical application that will be used by people that understand English and the target language, you might be OK with English error messages. If it's a message that will be seen by the end user, it should be translated.

What is Einval in C?

Macro: int EINVAL. “Invalid argument.” This is used to indicate various kinds of problems with passing the wrong argument to a library function. Macro: int EMFILE. “Too many open files.” The current process has too many files open and can't open any more.

What does errno 1 mean?

The errno(1) command can also be used to look up individual error numbers and names, and to search for errors using strings from the error description, as in the following examples: $ errno 2 ENOENT 2 No such file or directory $ errno ESRCH ESRCH 3 No such process $ errno -s permission EACCES 13 Permission denied List ...


1 Answers

FormatMessage is already used internally by Win32Exception. For example:

using System;

class Program {
    static void Main(string[] args) {
        var ex = new System.ComponentModel.Win32Exception(unchecked((int)0x80004005));
        Console.WriteLine(ex.Message);
        Console.ReadLine();
    }
}

Output: Unspecified error

Be sure to avoid bypassing the normal HRESULT checking that's done by the CLR in its COM interop layer. It uses IErrorInfo to get rich error text from the COM server. That gets you the 'real' error message rather the generic one.

like image 124
Hans Passant Avatar answered Sep 25 '22 01:09

Hans Passant