Yuval の回答は、リンクされたページに記載されているように、ログではなく、Web API によってキャッチされた未処理の例外への応答をカスタマイズするためのものです。詳細については、ページの「いつ使用するか」セクションを参照してください。ロガーは常に呼び出されますが、ハンドラーは応答を送信できる場合にのみ呼び出されます。つまり、ロガーを使用してログを記録し、ハンドラーを使用して応答をカスタマイズします。
ところで、私はアセンブリ v5.2.3 を使用しており、ExceptionHandler
クラスにはメソッドがありませんHandleCore
。同等のものは だと思いますHandle
。ただし、単純なサブクラス化ExceptionHandler
(Yuval の回答のように) は機能しません。私の場合、次のように実装する必要がありIExceptionHandler
ます。
internal class OopsExceptionHandler : IExceptionHandler
{
private readonly IExceptionHandler _innerHandler;
public OopsExceptionHandler (IExceptionHandler innerHandler)
{
if (innerHandler == null)
throw new ArgumentNullException(nameof(innerHandler));
_innerHandler = innerHandler;
}
public IExceptionHandler InnerHandler
{
get { return _innerHandler; }
}
public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
Handle(context);
return Task.FromResult<object>(null);
}
public void Handle(ExceptionHandlerContext context)
{
// Create your own custom result here...
// In dev, you might want to null out the result
// to display the YSOD.
// context.Result = null;
context.Result = new InternalServerErrorResult(context.Request);
}
}
ロガーとは異なり、ハンドラーを追加するのではなく、デフォルトのハンドラーを置き換えることによってハンドラーを登録することに注意してください。
config.Services.Replace(typeof(IExceptionHandler),
new OopsExceptionHandler(config.Services.GetExceptionHandler()));