使用WCF数据服务进行异常处理

Mar*_*nfy 8 exception-handling wcf-data-services

我想自定义从我的WCF数据服务抛出的异常/错误,以便客户尽可能多地获取有关哪些错误/缺少什么的信息.有关如何实现这一点的任何想法?

jai*_*mie 10

您需要做一些事情来确保异常通过HTTP管道传递到客户端.

  1. 您必须使用以下内容对DataService类进行属性:

    [ServiceBehavior(IncludeExceptionDetailInFaults = true)] public class MyDataService:DataService

  2. 您必须在配置中启用详细错误:

    public static void InitializeService(DataServiceConfiguration config){config.UseVerboseErrors = true; }

最好在其中抛出DataServiceException.WCF数据服务运行时知道如何将属性映射到HTTP响应,并始终将其包装在TargetInvocationException中.

[WebGet]
public Entity OperationName(string id)
{
    try
    {
        //validate param
        Guid entityId;
        if (!Guid.TryParse(id, out entityId))
            throw new ArgumentException("Unable to parse to type Guid", "id");

        //operation code
    }
    catch (ArgumentException ex)
    {
        throw new DataServiceException(400, "Code", ex.Message, string.Empty, ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过覆盖DataService中的HandleException来为客户端使用者解压缩,如下所示:

/// <summary>
/// Unpack exceptions to the consumer
/// </summary>
/// <param name="args"></param>
protected override void HandleException(HandleExceptionArgs args)
{
    if ((args.Exception is TargetInvocationException) && args.Exception.InnerException != null)
    {
        if (args.Exception.InnerException is DataServiceException)
            args.Exception = args.Exception.InnerException as DataServiceException;
        else
            args.Exception = new DataServiceException(400, args.Exception.InnerException.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)

有关详情,请参阅此处 ...


Jul*_*s A 0

您需要为此创建自定义异常。请在此处阅读这篇文章:为什么创建自定义异常?

您使用哪种语言进行开发?

如果您需要进一步的指导,请添加一些评论。