178

バックグラウンド

クライアント用の API サービス レイヤーを開発していますが、すべてのエラーをグローバルにキャッチしてログに記録するように依頼されました。

そのため、不明なエンドポイント (またはアクション) のようなものは、ELMAH を使用するか、次のようなものを に追加することで簡単に処理できますGlobal.asax

protected void Application_Error()
{
     Exception unhandledException = Server.GetLastError();
     //do more stuff
}

. . ルーティングに関連しない .unhandled エラーはログに記録されません。例えば:

public class ReportController : ApiController
{
    public int test()
    {
        var foo = Convert.ToInt32("a");//Will throw error but isn't logged!!
        return foo;
    }
}

[HandleError]このフィルターを登録して、属性をグローバルに設定しようとしました:

filters.Add(new HandleErrorAttribute());

ただし、すべてのエラーがログに記録されるわけではありません。

問題/質問

上記の呼び出しで生成されたようなエラーを傍受して/testログに記録するにはどうすればよいですか? この答えは明らかなはずですが、これまで考えられることはすべて試しました。

理想的には、要求しているユーザーの IP アドレス、日付、時刻など、エラー ログに何かを追加したいと考えています。また、エラーが発生したときにサポート スタッフに自動的に電子メールを送信できるようにしたいと考えています。これらのエラーが発生したときにインターセプトできれば、これらすべてを行うことができます。

解決しました!

私が受け入れた回答をしてくれた Darin Dimitrov のおかげで、これを理解することができました。 WebAPI は、通常の MVC コントローラーと同じ方法でエラーを処理しません。

うまくいったのは次のとおりです。

1) 名前空間にカスタム フィルターを追加します。

public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is BusinessException)
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent(context.Exception.Message),
                ReasonPhrase = "Exception"
            });

        }

        //Log Critical errors
        Debug.WriteLine(context.Exception);

        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent("An error occurred, please try again or contact the administrator."),
            ReasonPhrase = "Critical Exception"
        });
    }
}

2) フィルタをWebApiConfigクラスにグローバルに登録します。

public static class WebApiConfig
{
     public static void Register(HttpConfiguration config)
     {
         config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
         config.Filters.Add(new ExceptionHandlingAttribute());
     }
}

または、登録をスキップして、単一のコントローラーを[ExceptionHandling]属性で装飾することもできます。

4

5 に答える 5

82

以前の回答への追加として。

昨日、ASP.NET Web API 2.1 が正式にリリースされました。
例外をグローバルに処理する別の機会を提供します。
詳細はサンプルに記載されています。

簡単に言うと、グローバル例外ロガーおよび/またはグローバル例外ハンドラー (1 つだけ) を追加します。
それらを構成に追加します。

public static void Register(HttpConfiguration config)
{
  config.MapHttpAttributeRoutes();

  // There can be multiple exception loggers.
  // (By default, no exception loggers are registered.)
  config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger());

  // There must be exactly one exception handler.
  // (There is a default one that may be replaced.)
  config.Services.Replace(typeof(IExceptionHandler), new GenericTextExceptionHandler());
}

そして彼らの実現:

public class ElmahExceptionLogger : ExceptionLogger
{
  public override void Log(ExceptionLoggerContext context)
  {
    ...
  }
}

public class GenericTextExceptionHandler : ExceptionHandler
{
  public override void Handle(ExceptionHandlerContext context)
  {
    context.Result = new InternalServerErrorTextPlainResult(
      "An unhandled exception occurred; check the log for more information.",
      Encoding.UTF8,
      context.Request);
  }
}
于 2014-01-21T08:18:53.560 に答える
56

Web API が ASP.NET アプリケーション内でホストされている場合、Application_Errorイベントは、示したテスト アクションの例外を含め、コード内のすべての未処理の例外に対して呼び出されます。したがって、Application_Error イベント内でこの例外を処理するだけです。あなたが示したサンプルコードHttpExceptionでは、明らかにコードには当てはまらないタイプの例外のみを処理していConvert.ToInt32("a")ます。したがって、そこにすべての例外を記録して処理するようにしてください。

protected void Application_Error()
{
    Exception unhandledException = Server.GetLastError();
    HttpException httpException = unhandledException as HttpException;
    if (httpException == null)
    {
        Exception innerException = unhandledException.InnerException;
        httpException = innerException as HttpException;
    }

    if (httpException != null)
    {
        int httpCode = httpException.GetHttpCode();
        switch (httpCode)
        {
            case (int)HttpStatusCode.Unauthorized:
                Response.Redirect("/Http/Error401");
                break;

            // TODO: don't forget that here you have many other status codes to test 
            // and handle in addition to 401.
        }
        else
        {
            // It was not an HttpException. This will be executed for your test action.
            // Here you should log and handle this case. Use the unhandledException instance here
        }
    }
}

Web API での例外処理は、さまざまなレベルで実行できます。detailed articleさまざまな可能性について説明します。

  • グローバル例外フィルターとして登録できるカスタム例外フィルター属性

    [AttributeUsage(AttributeTargets.All)]
    public class ExceptionHandlingAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Exception is BusinessException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(context.Exception.Message),
                    ReasonPhrase = "Exception"
                });
            }
    
            //Log Critical errors
            Debug.WriteLine(context.Exception);
    
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent("An error occurred, please try again or contact the administrator."),
                ReasonPhrase = "Critical Exception"
            });
        }
    }
    
  • カスタム アクション インボーカー

    public class MyApiControllerActionInvoker : ApiControllerActionInvoker
    {
        public override Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
        {
            var result = base.InvokeActionAsync(actionContext, cancellationToken);
    
            if (result.Exception != null && result.Exception.GetBaseException() != null)
            {
                var baseException = result.Exception.GetBaseException();
    
                if (baseException is BusinessException)
                {
                    return Task.Run<HttpResponseMessage>(() => new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = new StringContent(baseException.Message),
                        ReasonPhrase = "Error"
    
                    });
                }
                else
                {
                    //Log critical error
                    Debug.WriteLine(baseException);
    
                    return Task.Run<HttpResponseMessage>(() => new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = new StringContent(baseException.Message),
                        ReasonPhrase = "Critical Error"
                    });
                }
            }
    
            return result;
        }
    }
    
于 2013-03-01T22:45:46.377 に答える
8

なぜ再スローするのですか?これは機能し、サービスがステータス 500 などを返します。

public class LogExceptionFilter : ExceptionFilterAttribute
{
    private static readonly ILog log = LogManager.GetLogger(typeof (LogExceptionFilter));

    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        log.Error("Unhandeled Exception", actionExecutedContext.Exception);
        base.OnException(actionExecutedContext);
    }
}
于 2013-10-30T11:38:01.543 に答える
2

次のようなハンドル エラー アクション フィルターのようなことを考えたことはありますか

[HandleError]
public class BaseController : Controller {...}

[HandleError]エラー情報やその他すべての詳細をログに記録できるカスタムバージョンを作成することもでき ます

于 2013-03-01T22:41:44.230 に答える
1

すべてを try/catch でラップし、未処理の例外をログに記録してから渡します。それを行うためのより良い組み込みの方法がない限り。

これが参照ですCatch All (handled or unhandled) Exceptions

(編集:ああAPI)

于 2013-03-01T22:37:12.067 に答える