简体   繁体   English

ac #dll将错误返回给调用应用程序的好方法是什么?

[英]What's a good way for a c# dll to return error to the calling application?

i'm writing a dll which is a wrapper to a access database. 我正在编写一个dll,它是访问数据库的包装器。 and i'm pretty new to c# in general as my background is in web development LAMP with perl, i'm not sure what's a good way to return error to a calling app in case they pass the wrong parameters to my functions or what not. 我一般都是c#的新手,因为我的背景是用perl进行Web开发LAMP,我不知道什么是将错误返回到调用应用程序的好方法,以防它们将错误的参数传递给我的函数或者什么不是。

I have no idea as of now except to probably do some msgbox or throw some exceptions but i don't know where to start looking. 我现在不知道除了可能做一些msgbox或抛出一些例外,但我不知道从哪里开始寻找。 Any help or resources would be more than useful :) 任何帮助或资源都将是有用的:)

thanks~ 谢谢〜

You probably don't want to display message dialogs from within your dll, that's the job of the client application, as part of the presentation layer. 您可能不希望在dll中显示消息对话框,这是客户端应用程序的工作,作为表示层的一部分。

.Net library assemblies typically bubble up exceptions to the host application, so that's the approach I'd look at. .Net库程序集通常会将异常冒泡到宿主应用程序中,所以这就是我要看的方法。

public static class LibraryClass
{
    public static void DoSomething(int positiveInteger)
    {
        if (positiveInteger < 0)
        {
            throw new ArgumentException("Expected a positive number", "positiveInteger");
        }
    }
}

Then it's up to your host application to handle those exceptions, logging and displaying them as appropriate. 然后由您的主机应用程序来处理这些异常,并根据需要记录和显示它们。

try
{
    LibraryClass.DoSomething(-3);
}
catch(ArgumentException argExc)
{
    MessageBox.Show("An Error occurred: " + argExc.ToString());
}

通常通过抛出ArgumentException或其子类之一来处理错误的参数。

You want to throw an exception. 你想抛出异常。

See 看到

http://msdn.microsoft.com/en-us/library/ms229007.aspx http://msdn.microsoft.com/en-us/library/ms229007.aspx

for the most common framework exceptions, such as ArgumentException and InvalidOperationException. 对于最常见的框架异常,例如ArgumentException和InvalidOperationException。 See also 也可以看看

http://msdn.microsoft.com/en-us/library/ms229030.aspx http://msdn.microsoft.com/en-us/library/ms229030.aspx

查看类库开发人员的设计指南: 错误提升和处理指南

Dlls generally should not create any kind of UI element to report an error. Dll通常不应创建任何类型的UI元素来报告错误。 You can Throw (same meaning as raise) many different kinds of exceptions, or create your own and the calling code (client) can catch and report to the user. 您可以抛出(与提升相同的意义)许多不同类型的异常,或创建您自己的异常,并且调用代码(客户端)可以捕获并向用户报告。

public void MyDLLFunction()
{
    try
    {
        //some interesting code that may
        //cause an error here
    }
    catch (Exception ex)
    {
        // do some logging, handle the error etc.
        // if you can't handle the error then throw to
        // the calling code
        throw;
        //not throw ex; - that resets the call stack
    }
}

抛出新的例外?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM