我有一個WebAPI
項目,並且正在將我的exception
捕獲從try/catch
捕獲到exception
filters
。以前當我用try/catch
塊我能夠訪問SQL
命令對象來獲取SQL
命令文本記錄到數據庫中。現在我轉移到異常過濾器,我不再能夠訪問SQL
命令對象。我所追求的是將上一次執行的SQL
命令傳遞給異常過濾器的方式,以便我仍然可以記錄它。傳遞值給ExceptionFilter
以前的代碼(try/catch塊)
public HttpResponseMessage API([FromBody] int roomID)
{
HttpResponseMessage msg = null;
SqlCommand comm = Common.Shared.ConnectDB();
try
{
List<Models.room> room = room(comm, roomID);
msg = Request.CreateResponse(HttpStatusCode.OK, room);
}
catch (CustomException ex)
{
msg = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
}
catch (Exception ex)
{
comm.Parameters.Clear();
var sourceFunction = "rooms";
var returnException = Common.Logging.CreateLog(ex, comm, sourceFunction);
msg = Request.CreateResponse(HttpStatusCode.InternalServerError, returnException);
}
finally
{
comm.Connection.Close();
}
return msg;
}
異常過濾器代碼
public class InternalServerErrorFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
Log.Error(context.Exception, "Exception Information");
context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
控制器異常過濾器
[InternalServerErrorFilter]
[HttpPost]
public HttpResponseMessage API([FromBody] int roomID)
{
HttpResponseMessage msg = null;
SqlCommand comm = Common.Shared.ConnectDB();
try
{
List<Models.room> room = room(comm, roomID);
msg = Request.CreateResponse(HttpStatusCode.OK, room);
}
finally
{
comm.Connection.Close();
}
return msg;
}
這將適用於SQL異常。不過我也希望能搶SQL命令其他異常,如由數據讀取器等,這些不亂扔SQL異常,因此我不會得到其使用的數據讀取器等 – Nathan
命令字符串拋出@Nathan,那麼你可以選擇第二個選項。但是,您需要手動處理由數據讀取器引發的異常。你不必捕獲'SqlException',你可以捕獲'Exception'。 –