VB.NET 异常处理返回数据集而不是字符串的东西

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14452054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:58:37  来源:igfitidea点击:

VB.NET exception handling for something that returns a data set instead of a string

vb.netexceptiontypesexception-handlingdataset

提问by Kaycee Enerva

My program is throwing an error I should handle. But I cannot return a string message because the it is a function that returns a dataset:

我的程序抛出了一个我应该处理的错误。但我无法返回字符串消息,因为它是一个返回数据集的函数:

Public Function getUserInfo(ByValue testUserIdAs String) As DataSet
    Dim dsUseInfo As DataSet = New DataSet()
    Try
        Dim objTestWs As New TestWebService.UserMaintenanceSoapClient
        dsUseInfo = objTestWs.dsGetUserInfo(TestOU, PAC, paramUserID)
        Return (dsUseInfo)
    Catch ex As Exception

        ' TEST FIX ERROR HANDLING -LIWM Please search how to return custom error. I want to return "userid already exists"
        Throw
    End Try

I was thinking of putting in:

我想输入:

If error
then return "Error Message"

But I can't return it as type string.

但我不能将它作为字符串类型返回。

回答by Heinzi

It looks like you don't really know what to do with the exception in getUserInfoand just want to pass it on to the outer function.

看起来您真的不知道如何处理异常,getUserInfo只想将其传递给外部函数。

Well, here's the great thing about exceptions: They are passed on automatically!There's nothing you need to do, and, in particular, you do not need to use the return value of the function for that. Just don't catch the exception until you know what to do with it.

好吧,这是关于异常的伟大之处:它们会自动传递!您无需执行任何操作,特别是,您无需为此使用函数的返回值。在您知道如何处理异常之前不要捕捉异常。



For example, in your case, just handle the error in the callingfunction instead:

例如,在您的情况下,只需处理调用函数中的错误:

  • Remove the error handling code from the called function:

    Public Function getUserInfo(ByValue testUserIdAs String) As DataSet
        Dim objTestWs As New TestWebService.UserMaintenanceSoapClient
        Return objTestWs.dsGetUserInfo(TestOU, PAC, paramUserID)
    End Function
    
  • and add it to the calling function, i.e., replace

    ...
    Dim dsUserInfo As DataSet
    dsUserInfo = getUserInfo()
    ...
    

    with

    ...
    Dim dsUserInfo As DataSet
    Try
        dsUserInfo = getUserInfo()
    Catch ex As Exception
        ' Do whatever you want to do in case of an error here
        MsgBox("Could not get User Info: " & ex.Message)
        Return
    End Try
    ...
    
  • 从被调用的函数中删除错误处理代码:

    Public Function getUserInfo(ByValue testUserIdAs String) As DataSet
        Dim objTestWs As New TestWebService.UserMaintenanceSoapClient
        Return objTestWs.dsGetUserInfo(TestOU, PAC, paramUserID)
    End Function
    
  • 并将其添加到调用函数中,即替换

    ...
    Dim dsUserInfo As DataSet
    dsUserInfo = getUserInfo()
    ...
    

    ...
    Dim dsUserInfo As DataSet
    Try
        dsUserInfo = getUserInfo()
    Catch ex As Exception
        ' Do whatever you want to do in case of an error here
        MsgBox("Could not get User Info: " & ex.Message)
        Return
    End Try
    ...
    


One you are familiar with this technique, you can go on to more advanced topics like throwing your own exception, like @Justin suggested. Just make sure to include information about the original cause of the errorin your own exception, for example, by copying parts of ex.Messageinto your own exception message and setting the innerExceptionproperty.

如果您熟悉这种技术,您可以继续讨论更高级的主题,例如抛出自己的异常,如@Justin 建议的那样。只需确保在您自己的异常中包含有关错误原始原因的信息,例如,通过将部分内容复制ex.Message到您自己的异常消息中并设置innerException属性。

回答by Justin Edwards

You could throw a generic exception:

您可以抛出一个通用异常:

Public Function getUserInfo(ByValue testUserIdAs String) As DataSet
    Dim dsUseInfo As DataSet = New DataSet()
    Try
        Dim objTestWs As New TestWebService.UserMaintenanceSoapClient
        dsUseInfo = objTestWs.dsGetUserInfo(TestOU, PAC, paramUserID)
        Return (dsUseInfo)
    Catch ex As Exception
        Throw New Exception("Custom message", ex)
    End Try

This will set the message on the exception you catch up the call stack to be "Custom Message" with an inner exceptionthat contains the original exception which was thrown.

这会将您捕获调用堆栈的异常上的消息设置为“自定义消息”,其中包含一个包含抛出的原始异常的内部异常

Or you could create a custom exception(by inheriting from System.Exception) elsewhere if you want to throw a more expressively named exception(and so you don't have to catch all exceptions when you want to catch this custom type).

或者,如果您想抛出一个更具有表现力的命名异常,您可以在其他地方创建一个自定义异常(通过从 System.Exception 继承)(因此当您想要捕获此自定义类型时,您不必捕获所有异常)。

Public Class UserInfoNotFoundException
    Inherits System.Exception

    Public Sub New()
    End Sub

    Public Sub New(message As String)
        MyBase.New(message)
    End Sub

    Public Sub New(message As String, innerException As Exception)
        MyBase.New(message, innerException)
    End Sub
End Class

You could then, for example, throw a UserInfoNotFoundException.

例如,然后您可以抛出 UserInfoNotFoundException。

回答by specializt

I would change the whole approach to exceptions and errors:

我会改变处理异常和错误的整个方法:

  • Create a new assembly (project) and reference it in your application
  • Declare new shared events which accept your personal datatype (referenced assembly)
  • Declare at least one shared function (referenced assembly) which does a RaiseEvent on your new events
  • Add handlers (main application) for your shared events in which you react accordingly
  • Call your function from within the main application, passing your own parameters whenever you need to throw errors / exceptions
  • 创建一个新的程序集(项目)并在您的应用程序中引用它
  • 声明接受您的个人数据类型的新共享事件(引用程序集)
  • 声明至少一个共享函数(引用程序集),它对新事件执行 RaiseEvent
  • 为您做出相应反应的共享事件添加处理程序(主应用程序)
  • 从主应用程序中调用您的函数,在您需要抛出错误/异常时传递您自己的参数

This way you circumvent many programming mistakes andcentralize error and exception-handling.

通过这种方式,您可以避免许多编程错误集中错误和异常处理。

Public Module IDENTIFIERS

    Public Enum EvtMsg
        ERR_MYERR
        ERR_MYERR2
    End Enum

    Public Enum EvtClass
        EXCEPTION
        ERR
    End Enum
End Module

Public Class Events

    Shared Event Err(ByVal code As EvtMsg)
    Shared Event Exception(ByRef iEx As Exception)

    Public Shared Sub Raise(ByVal iEvtClass As EvtClass, ByVal iMsg As EvtMsg, Optional ByRef iEx As Exception = Nothing)
        If Not [Enum].IsDefined(GetType(EvtClass), iEvtClass) Then
            Dim ex As New ArgumentOutOfRangeException("unbekannte Event-Klasse '" & iEvtClass.ToString & "' übergeben", "iEvtClass")
            RaiseEvent Exception(ex)
        End If
        If Not [Enum].IsDefined(GetType(EvtMsg), iMsg) Then
            Dim ex As New ArgumentOutOfRangeException("unbekannte Event-Msg '" & iMsg.ToString & "' übergeben", "iMsg")
            RaiseEvent Exception(ex)
        End If

        Select Case iEvtClass
            Case EvtClass.ERR
                RaiseEvent Err(iMsg)
            Case EvtClass.EXCEPTION
                If iEx IsNot Nothing Then
                    RaiseEvent Exception(iEx)
                Else
                    Dim ex As New MissingFieldException("Raise() ohne Exception aufgerufen, iMsg : " & iMsg & "EvtClass : " & iEvtClass.ToString(), "iEx")
                    RaiseEvent Exception(ex)
                End If
        End Select
    End Sub

End Class

And now you can easily use these error-handlers in any assembly which references your error-assembly:

现在您可以在任何引用您的错误程序集的程序集中轻松使用这些错误处理程序:

Constructor

构造函数

AddHandler Events.Err, AddressOf Err
AddHandler Events.Exception, AddressOf Except

Class-body

类体

Private Sub Except(ByRef iEx As Exception)
    'do your stuff here
End Sub

Private Sub Err(ByVal Err As EvtMsg)
    'do your stuff here
End Sub