WebAPIメモ:WebApi異常処理
テストコードリンク
異常フィルタ特性:ExceptionFilterAttribute異常フィルタ特性:メソッドの実行中に異常が発生する、処理される、限界がある:コントローラがインスタンス化された後、メソッドの実行が完了するまで、発生した異常がWebApiConfigに捉えられる.cs Registerメソッドに登録するすべてのwebapi異常キャプチャを実現する:config.Filters.Add(new CustomExceptionAttribute()); コントローラ名にプロパティ[CustomExceptionAttribute]を追加して、このコントローラ登録webapi異常キャプチャを実現します.また、apiメソッドにプロパティを追加する[CustomExceptionAttribute]登録例外キャプチャ例外がtry{}catch{}で処理された場合、ExceptionFilterAttribute例外フィルタプロパティは例外をキャプチャしません
グローバル例外処理:コントローラのインスタンス化/メソッドエラーGlobalExceptionHandler:ExceptionHandler;例外フィルタのプロパティは上書きされません:WebApiConfigでExceptionFilterAttribute.cs Registerメソッドに登録してすべてのwebapiグローバル異常キャプチャを実現する:config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
異常フィルタ特性:ExceptionFilterAttribute異常フィルタ特性:メソッドの実行中に異常が発生する、処理される、限界がある:コントローラがインスタンス化された後、メソッドの実行が完了するまで、発生した異常がWebApiConfigに捉えられる.cs Registerメソッドに登録するすべてのwebapi異常キャプチャを実現する:config.Filters.Add(new CustomExceptionAttribute()); コントローラ名にプロパティ[CustomExceptionAttribute]を追加して、このコントローラ登録webapi異常キャプチャを実現します.また、apiメソッドにプロパティを追加する[CustomExceptionAttribute]登録例外キャプチャ例外がtry{}catch{}で処理された場合、ExceptionFilterAttribute例外フィルタプロパティは例外をキャプチャしません
public class CustomExceptionAttribute : ExceptionFilterAttribute
{
///
/// api
/// api ( )
///
///
///
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
Console.WriteLine($"{actionExecutedContext.Request.RequestUri.AbsoluteUri}:{actionExecutedContext.Exception.Message}");
// api
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(
HttpStatusCode.OK, new
{
Result = false,
Msg = $"{" :" + actionExecutedContext.Request.RequestUri.AbsoluteUri}:{actionExecutedContext.Exception.Message}"
});
//base.OnException(actionExecutedContext);
}
}
グローバル例外処理:コントローラのインスタンス化/メソッドエラーGlobalExceptionHandler:ExceptionHandler;例外フィルタのプロパティは上書きされません:WebApiConfigでExceptionFilterAttribute.cs Registerメソッドに登録してすべてのwebapiグローバル異常キャプチャを実現する:config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
///
///
///
public class GlobalExceptionHandler : ExceptionHandler
{
/////
/////
/////
/////
/////
//public override bool ShouldHandle(ExceptionHandlerContext context)
//{
// return context.Request.RequestUri.AbsoluteUri.Contains("api") && base.ShouldHandle(context);
//}
///
///
///
///
public override void Handle(ExceptionHandlerContext context)
{
Console.WriteLine(context.Exception.Message);
//
context.Result = new ResponseMessageResult(context.Request.CreateResponse(
HttpStatusCode.OK, new
{
Result = false,
Msg = $"{" :" + context.Exception.Message}"
}));
}
}