在 Web API 中使用 ExceptionFilterAttribute

trx*_*trx 7 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 });
    }
}
Run Code Online (Sandbox Code Playgroud)

并在 Gloal.asax.cs 中注册它们,例如

GlobalConfiguration.Configuration.Filters.Add(new BALExceptionFilterAttribute());
Run Code Online (Sandbox Code Playgroud)

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

    [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;
               }
        }
Run Code Online (Sandbox Code Playgroud)

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

Igo*_*gor 5

//throws the exception
throw new BALExceptionFilterAttribute();
Run Code Online (Sandbox Code Playgroud)

这将产生编译器错误。异常过滤器属性是在发生异常时做一些事情,以便您可以以通用方式处理它,例如重定向到错误页面或在 json 响应中发回通用异常消息等。异常过滤器属性本身不是异常,它处理异常。

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

如果你想要一个BALException类型然后创建一个。

public class BALException : Exception { /* add properties and constructors */}
Run Code Online (Sandbox Code Playgroud)

现在你可以扔了

throw new BALException();
Run Code Online (Sandbox Code Playgroud)

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