在Web API中使用ExceptionFilterAttribute

时间:2016-11-22 13:34:51

标签: c# asp.net asp.net-mvc asp.net-web-api

我正在尝试在创建的Web API中实现错误处理,需要以JSON格式返回异常详细信息。我创建了像

这样的BALExceptionFilterAttribute
public class BALExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        base.OnException(actionExecutedContext);
        actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, new { error = actionExecutedContext.Exception.Message });
    }
}

并在Gloal.asax.cs中注册了

GlobalConfiguration.Configuration.Filters.Add(new BALExceptionFilterAttribute());

在我的控制器中,我想抛出异常,如

    [HttpGet]
    [BALExceptionFilter]
    public HttpResponseMessage Getdetails(string ROOM, DateTime DOB_GT)
    {
        if (string.IsNullOrEmpty(ROOM) 
        {
            return Request.CreateResponse(new { error = "Input paramete cannot be Empty or NULL" });
        }
            //throws the exception
            throw new BALExceptionFilterAttribute();

            List<OracleParameter> prms = new List<OracleParameter>();
            List<string> selectionStrings = new List<string>();
            prms.Add(new OracleParameter("ROOM", OracleDbType.Varchar2, ROOM, ParameterDirection.Input));
            prms.Add(new OracleParameter("DOB_GT", OracleDbType.Date, DOB_GT, ParameterDirection.Input));
            string connStr = ConfigurationManager.ConnectionStrings["TGSDataBaseConnection"].ConnectionString;
            using (OracleConnection dbconn = new OracleConnection(connStr))
            {
                DataSet userDataset = new DataSet();
                var strQuery = "SELECT * from LIMS_SAMPLE_RESULTS_VW where ROOM = :ROOM and DOB > :DOB_GT ";
                var returnObject = new { data = new OracleDataTableJsonResponse(connStr, strQuery, prms.ToArray()) };
                var response = Request.CreateResponse(HttpStatusCode.OK, returnObject, MediaTypeHeaderValue.Parse("application/json"));
                ContentDispositionHeaderValue contentDisposition = null;
                if (ContentDispositionHeaderValue.TryParse("inline; filename=TGSData.json", out contentDisposition))
                {
                    response.Content.Headers.ContentDisposition = contentDisposition;
                }
                return response;
               }
        }

但它在throw new BALExceptionFilterAttribute();上显示错误 Error 1 The type caught or thrown must be derived from System.Exception

2 个答案:

答案 0 :(得分:3)

//throws the exception
throw new BALExceptionFilterAttribute();

这将产生编译器错误。异常过滤器属性是在发生异常时执行某些操作,因此您可以以通用方式处理它,例如重定向到错误页面或在json响应中发回回一般异常消息等。异常过滤器属性本身也不例外,它处理异常。

因此throw new BALExceptionFilterAttribute();无效,因为BALExceptionFilterAttribute不是例外。

如果您想要BALException类型,请创建一个。

public class BALException : Exception { /* add properties and constructors */}

现在你可以抛出它

throw new BALException();

然后您可以配置BALExceptionFilterAttribute以便在此异常到达过滤器时执行某些操作(未在控制器中捕获)。

答案 1 :(得分:2)

# Path to the local Maven repository which is used to avoid downloading # artifacts when they already exist locally. # The value of this property will be extracted from the settings.xml file # above, or defaulted to: # System.getProperty( "user.home" ) + "/.m2/repository" # leaving this option commented makes the system dependent on external configuration, which is not always desired # "localRepository" is the target location for artifacts downloaded from "remote repositories", it's not # searched for already available artifacts, unless added explicitly to "defaultRepositories" # by default internal local repository is used to have behavior independent of the content of ~/.m2/repository org.ops4j.pax.url.mvn.localRepository = ${karaf.data}/repository 继承自ExceptionFilterAttribute而不是System.Attribute

MSDN Reference

为什么你没有得到编译器错误我不太确定。

修改

过滤器允许您在各个点挂接到ASP.NET管道以编写处理事件的代码。异常处理就是一个很好的例子。

如果您还需要自定义异常,那么您可以创建一个额外的类,例如System.Exception,尽管按照描述查看您的用例,您可能能够使用现有的框架异常。

我完全清楚你为什么要把它扔进原始帖子中所写的工作流程的正常执行中。