gpt4 book ai didi

c# - 在 Web API 中使用 ExceptionFilterAttribute

转载 作者:太空狗 更新时间:2023-10-30 00:49:05 30 4
gpt4 key购买 nike

我正在尝试在创建的 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());

在我的 Controller 中,我想抛出异常

    [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();错误 1 ​​捕获或抛出的类型必须派生自 System.Exception

最佳答案

//throws the exception
throw new BALExceptionFilterAttribute();

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

因此 throw new BALExceptionFilterAttribute(); 无效,因为 BALExceptionFilterAttribute 不是异常。

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

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

现在你可以扔了

throw new BALException();

然后您可以配置 BALExceptionFilterAttribute 以在该异常到达过滤器(未在 Controller 中捕获)的情况下执行某些操作。

关于c# - 在 Web API 中使用 ExceptionFilterAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40743241/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com