Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ExceptionFilterAttribute in Web API

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

like image 344
trx Avatar asked Nov 22 '16 13:11

trx


People also ask

What are exception filters in web API?

With exception filters, you can customize how your Web API handles several exceptions by writing the exception filter class. Exception filters catch the unhandled exceptions in Web API. When an action method throws an unhandled exception, execution of the filter occurs.

How do I create an exception filter in MVC?

The simplest way to write an exception filter is to derive from the System.Web.Http.Filters.ExceptionFilterAttribute class and override the OnException method. Exception filters in ASP.NET Web API are similar to those in ASP.NET MVC.

How to implement the exception handler in web API?

To implement the ExceptionHandler, you can use the following code: Note: The exception handler should be registered. Web APIs have an existing exception handler class but don’t support multiple exception handlers. Therefore, you need to replace the existing class with your custom exception handler class.

How to register exception filter in Salesforce?

There are many ways to register exception filter but the developers generally follow three approaches to register filter. Decorate Action with exception filter. Decorate Controller with exception filter. Filter Register globally. To apply the exception filter to the specific action, the action needs to decorate with this filter attribute.


2 Answers

//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).

like image 99
Igor Avatar answered Oct 23 '22 17:10

Igor


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.

like image 37
ste-fu Avatar answered Oct 23 '22 16:10

ste-fu