简体   繁体   English

ASP.NET传递错误消息

[英]ASP.NET Pass Error Messages

This is probably going to end up as a stupid question, but countless research has offered me no results. 这可能最终会成为一个愚蠢的问题,但是无数的研究没有给我任何结果。

I know there are different types of errors I want to check for, and when I should be throwing an exception for "exceptional" errors, and that I should create validating functions for input and other checks. 我知道我要检查的错误类型不同,何时应该为“异常”错误引发异常,并且应该为输入和其他检查创建验证函数。

My problem is, how do I send an error back to a page when the data entered fails in a separate class? 我的问题是,当输入的数据在单独的类中失败时,如何将错误发送回页面?

For Example: 例如:

  • User input entered in Page1.aspx, click calls Submit() in Class.vb 在Page1.aspx中输入用户输入,单击在Class.vb中调用Submit()
  • Class.vb finds that input is invalid Class.vb发现输入无效
  • How do I update Page1.aspx label to say "Hey, that is not right". 如何将Page1.aspx标签更新为“嘿,那不对”。

I can do it on inline page, no problem, its passing it through a separate class that's causing me issues... Maybe I'm not even thinking of this correctly. 我可以在内联页面上完成它,没问题,将它传递给一个单独的类,这会引起我的问​​题……也许我什至没有正确地考虑这一点。

Any points in the right direction would be of huge help. 朝正确方向的任何观点都会有很大帮助。

Thanks for the help in advance. 我在这里先向您的帮助表示感谢。

The simplest solution is to have Submit() return a boolean indicating whether there was an error or not: 最简单的解决方案是让Submit()返回一个布尔值,该布尔值指示是否存在错误:

If class.Submit() = False Then
    lblError.Text = "Hey, that is not right."
End If

It is a good practice to put your class in charge of its own errors, in which case you would expose an error message property: 最好让类负责自己的错误,在这种情况下,您将公开错误消息属性:

If class.Submit() = False Then
    lblError.Text = class.GetErrorMessage()
End If

The Submit function would look something like this: Submit函数将如下所示:

Public Function Submit() As Boolean
    Dim success As Boolean = False
    Try
        ' Do processing here.  Depending on what you do, you can
        ' set success to True or False and set the ErrorMessage property to
        ' the correct string.
    Catch ex As Exception
        ' Check for specific exceptions that indicate an error.  In those
        ' cases, set success to False.  Otherwise, rethrow the error and let
        ' a higher up error handler deal with it.
    End Try

    Return success
End Function

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

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