LoginSignup
0
0

More than 5 years have passed since last update.

学んだこと(Web アプリでの未処理例外ハンドル)

Posted at
  • Web アプリでの未処理例外ハンドルの方法

    https://www.c-sharpcorner.com/article/exception-handling-in-asp-net-web-api/ を参考に

    • コントローラ処理の未処理例外にはExceptionFilterを使用する。
      1. ExceptionFilterAttribute の派生クラスを作成する。
      2. 作成した派生クラスを使用するよう、Configurationに登録する
    • ExceptionFilterでキャッチできない例外にはExceptionHandlerを使用する。
      1. ExceptionHandler の派生クラスを作成する。
      2. 作成した派生クラスを使用するよう、Configurationに登録する
  • サンプル

public class CustomExceptionFilter : ExceptionFilterAttribute
    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        string exceptionMessage = string.Empty;
        if (actionExecutedContext.Exception.InnerException == null)
        {
            exceptionMessage = actionExecutedContext.Exception.Message;
        }
        else
        {
            exceptionMessage = actionExecutedContext.Exception.InnerException.Message;
        }

        // Logging(exceptionMessage);
    }
}

public class CustomExceptionHandler: ExceptionHandler  
{
    public async override Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        // Logging(context.Exception);
    }
}

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // 例外ハンドラの登録
        GlobalConfiguration.Configuration.Filters.Add(new CustomExceptionFilter());
        GlobalConfiguration.Configuration.Services.Replace(typeof(IExceptionHandler), new CustomExceptionHandler());
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0