【问题标题】:How to intercept WCF faults and return custom response instead?如何拦截 WCF 错误并返回自定义响应?
【发布时间】:2011-06-10 16:13:37
【问题描述】:

考虑以下非常基本的 WCF 服务实现:

public enum TransactionStatus 
{
    Success = 0,
    Error = 1
}

public class TransactionResponse
{
    public TransactionStatus Status { get; set; }
    public string Message { get; set; }
}


[ServiceContract]
[XmlSerializerFormat]
public interface ITestService
{
    [OperationContract]
    TransactionResponse DoSomething(string data);
}   

public class TestService : ITestService
{
    public TransactionResponse DoSomething(string data)
    {
        var result = ProcessData(data); // may throw InvalidOperationException
        return new TransactionResponse() 
        {
            Status = TransactionStatus.Success,
            Message = result                
        };            
    }

    private string ProcessData(string data) 
    {
        if (data = "foobar")
            throw new InvalidOperationException();

        return data;        
    }        
}

在 DoSomething 方法确实抛出 InvalidOperationException 的情况下,我想拦截错误并返回 TransactionResponse 对象,而不是让 WCF 向客户端引发 FaultException。我怎样才能做到这一点,而不用在一个巨大的 try catch 语句中包围每个方法体?有什么地方我可以挂钩吗?我可以使用某种属性或其他东西来做到这一点吗?可以使用 ASP.NET MVC 演示我想如何处理它的示例:

public class ApiController : BaseController
{
    protected override void OnException(ExceptionContext filterContext)
    {
        var ex = filterContext.Exception;
        var message = HttpContext.IsDebuggingEnabled ? ex.ToString() : ex.Message;

        _logger.Error("Error processing request for controller {0}, action {1}",
            filterContext.RequestContext.RouteData.Values["controller"],
            filterContext.RequestContext.RouteData.Values["action"]);

        _logger.Error(ex.ToString());
        filterContext.ExceptionHandled = true;
        filterContext.Result = ToXml(new ApiResult(false)
        {
            Message = message
        });
    }

    // ...
}

在 MVC 中使用上述方法,我可以确保无论哪个控制器操作引发异常,我都可以处理它并返回包含必要信息的适当格式的 ActionResult。有没有办法用 WCF 做这种事情?

【问题讨论】:

    标签: wcf exception-handling


    【解决方案1】:

    查看WCF IErrorHandler 接口 - 它允许您在服务实现中集中定义一种方式来捕获所有异常并将它们吞下,或者将它们转换为 WCF 友好的 SOAP 异常。这将确保客户端和服务器之间的通道没有故障,例如本次调用失败后仍可使用。

    我不明白您为什么要“捕捉” SOAP 错误并将其转换为其他错误……我也不知道 WCF 会为您提供任何支持。基本假设是:捕获 .NET 异常并将其转换为可互操作的 SOAP 错误

    【讨论】:

    • 这里有一个场景:有时你必须为一个对他们的服务规范做出奇怪决定的企业提供服务(例如,将整个重要数据作为 XML 字符串返回),他们通常希望你永远不会抛出任何 SoapFault 但返回带有错误代码的内容。这种情况首先把我带到了这里:p
    • 正是我的情况:'(
    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 2013-06-09
    • 2020-09-22
    • 2021-01-08
    • 2017-09-20
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多