在Web API中使用ExceptionFilterAttribute [英] Using ExceptionFilterAttribute in Web API

查看:354
本文介绍了在Web API中使用ExceptionFilterAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

并像

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

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

推荐答案

//throws the exception
throw new BALExceptionFilterAttribute();

这将生成编译器错误.异常过滤器属性用于在发生异常的情况下执行某些操作,因此您可以采用通用的方式进行处理,例如重定向到错误页面或在json响应中发送回通用的异常消息等.异常过滤器属性本身不是异常,它会处理异常.

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.

所以throw new BALExceptionFilterAttribute();无效,因为BALExceptionFilterAttribute也不例外.

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

如果要使用BALException类型,请创建一个.

If you want a BALException type then create one.

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

现在您可以扔了

throw new BALException();

,然后您可以将BALExceptionFilterAttribute配置为在此异常到达过滤器(未在控制器中捕获)的情况下执行某些操作.

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

这篇关于在Web API中使用ExceptionFilterAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆