0

我有一个将记录提交到数据库的自定义 Web 服务,

提交给表的 JF_ID 值引用主/源表的 JF_ID 值。因此,如果用户尝试提交不存在的 JF_ID,则会捕获 sql 异常,说“违反参照完整性等......

这是我的网络服务的样子:

[WebService(Namespace = "http://microsoft.com/webservices/")]
class POReqEntryForm : WebService 
{
    [WebMethod(Description = "Submits data to [Req_entry].")]
    public void AddRecordPOReqIdEntry(int JF_ID, int ReqId, string PONum, string POLineNum, float POAmount, string Submitter, string DateSubmitted)
    {

        string connectionString =
          ConfigurationManager.ConnectionStrings["REQdb"].ConnectionString;

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = System.Data.CommandType.Text;


            cmd.CommandText = "INSERT INTO [REQdb].[dbo].[Req_entry] "
                + "(JF_ID, Req_id, Po_num, Po_line_num, po_amount, Submitter, Date_Submitted ) "
                + "VALUES (@JF_ID, @ReqId, @PONum, @POLineNum, @POAmount, @Submitter, @DateSubmitted)";

            cmd.Parameters.AddWithValue("JF_ID", JF_ID);
            cmd.Parameters.AddWithValue("ReqId", ReqId);
            cmd.Parameters.AddWithValue("PONum", PONum);
            cmd.Parameters.AddWithValue("POLineNum", POLineNum);
            cmd.Parameters.AddWithValue("POAmount", POAmount);
            cmd.Parameters.AddWithValue("Submitter", Submitter);
            cmd.Parameters.AddWithValue("DateSubmitted", DateSubmitted);

            cmd.Connection = conn;

            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();

            }

            catch
            {
                // Handle the error using your own preferred error-handling method
            }
            finally
            {
                conn.Close();
            }
        }


    }

}

用户可能有许多故障数据条目。例如,用户输入字符串而不是整数值,如果他尝试提交不存在的 JF_ID 的条目,则违反参照完整性。

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Req_Entry_JF_ID". The conflict occurred in database "REQdb", table "dbo.Main_Form", column 'JF_ID'.

如何确保在捕获此类 SQL 异常时,从我的 Web 服务传递用户友好的自定义错误消息(例如输入的 ID 不存在。数据插入失败!)。最后,我想将此友好的错误消息传递给 InfoPath 客户端。

非常感谢。

4

1 回答 1

1

你想要做的就是“引发肥皂异常”。你可以在这里阅读更多关于它的信息。使用以下代码:

    /// <summary>
    /// Creates a custom SoapException to submit the client detailed information about the thrown errors
    /// </summary>
    /// <param name="uri">the name of the called method</param>
    /// <param name="webServiceNamespace">iShare_Services</param>
    /// <param name="errorMessage">the thrown error message</param>
    /// <param name="errorSource">the method which caused the error</param>
    /// <param name="code">Server or Client error?</param>
    /// throw RaiseException("MyMethod", "Service", ee.Message,
    /// ee.TargetSite.Name, FaultCode.Client);
    /// <returns></returns>
    public SoapException RaiseException(string uri, string webServiceNamespace,
        string errorMessage, string errorSource, FaultCode code)
    {
        XmlQualifiedName faultCodeLocation = null;
        //Identify the location of the FaultCode
        switch (code)
        {
            case FaultCode.Client:
                faultCodeLocation = SoapException.ClientFaultCode;
                break;
            case FaultCode.Server:
                faultCodeLocation = SoapException.ServerFaultCode;
                break;
        }

        XmlDocument xmlDoc = new XmlDocument();
        //Create the Detail node
        XmlNode rootNode = xmlDoc.CreateNode(XmlNodeType.Element, SoapException.DetailElementName.Name, SoapException.DetailElementName.Namespace);
        //Build specific details for the SoapException

        //Add first child of detail XML element.
        XmlNode errorNode = xmlDoc.CreateNode(XmlNodeType.Element, "Error", webServiceNamespace);

        //Create and set the value for the ErrorMessage node
        XmlNode errorMessageNode = xmlDoc.CreateNode(XmlNodeType.Element, "ErrorMessage", webServiceNamespace);

        errorMessageNode.InnerText = errorMessage;

        //Create and set the value for the ErrorSource node
        XmlNode errorSourceNode = xmlDoc.CreateNode(XmlNodeType.Element, "ErrorSource", webServiceNamespace);

        errorSourceNode.InnerText = errorSource;

        //Append the Error child element nodes to the root detail node.
        errorNode.AppendChild(errorMessageNode);
        errorNode.AppendChild(errorSourceNode);

        //Append the Detail node to the root node
        rootNode.AppendChild(errorNode);

        //Construct the exception
        SoapException soapEx = new SoapException(errorMessage, faultCodeLocation, uri, rootNode);

        //Raise the exception  back to the caller
        return soapEx;
    }

并在您的捕获中调用它,如下所示:

        catch (Exception e)
        {
            var userFriendlyMessage = "this is a user friendly exception!";
            throw RaiseException("MyMethod", this.GetType().Namespace, userFriendlyMessage, e.Source, FaultCode.Client);
        }

在 InfoPath 中,您只需添加 WebService 引用(检索和不提交)并将消息绑定到所需的字段。

您还可以扩展 RaiseException 代码,它将 ex.Message 和用户友好的消息发送回客户端 (InfoPath)。您可能想要创建一个“管理视图”,以允许您查看实际的异常。

于 2012-11-23T08:45:05.643 回答