我試圖在創建的Web API中實現錯誤處理,需要以JSON格式返回異常詳細信息。我創建了BALExceptionFilterAttribute像在Web API中使用ExceptionFilterAttribute
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());
在我的控制器,我想拋出像
[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;
}
}
的例外,但它顯示的錯誤like on throw new BALExceptionFilterAttribute();
Error 1 The type caught or thrown must be derived from System.Exception
是的,它確實會引發編譯器錯誤。我該如何處理這個問題 – trx