Using ExceptionFilterAttribute in Web API

家住魔仙堡 提交于 2020-01-14 12:53:33

问题


I am trying to implement the error handling in the created Web API, need to return the exception details in JSON format. I created the BALExceptionFilterAttribute like

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 });
    }
}

And registered them in Gloal.asax.cs like

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

In my Controllers I want to throw the exception like

    [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;
               }
        }

But it shows error like on the throw new BALExceptionFilterAttribute(); Error 1 The type caught or thrown must be derived from System.Exception


回答1:


//throws the exception
throw new BALExceptionFilterAttribute();

That will generate a compiler error. The exception filter attribute is to do something in the event of an exception so you can handle it in a generic manner like redirecting to an error page or sending back a generic exception message in the json response, etc. The exception filter attribute itself is not an exception, it handles the exception.

So throw new BALExceptionFilterAttribute(); is not valid because BALExceptionFilterAttribute is not an exception.

If you want a BALException type then create one.

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

and now you can throw it

throw new BALException();

and then you can configure BALExceptionFilterAttribute to do something in the event that this exception reaches the filter (is not caught in the controller).




回答2:


ExceptionFilterAttribute inherits from System.Attribute not System.Exception.

MSDN Reference

Why you don't get a compiler error I am not so sure.

EDIT

A filter allows you to hook into the ASP.NET pipeline at various points to write code that handles events. Exception handling is a good example of that.

If you need a custom exception as well then you can create an extra class for example public class BALException : Exception although looking at your use case as described you may well be able to use an existing framework exception.

I am at all clear as to why you want to throw it in the normal execution of you work flow as written in the original post.



来源:https://stackoverflow.com/questions/40743241/using-exceptionfilterattribute-in-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!