public void ShouldProperlyExecuteExceptionHandlers() { var storage = new GlobalExceptionBuilderStorage(); Func <ArgumentNullException, IActionResult> func = x => new ObjectResult(x.Message); storage.ExceptionHandlers.Add(typeof(ArgumentNullException), func); var filter = CreateFilter(storage); var actionContext = new ActionContext { HttpContext = new DefaultHttpContext(), RouteData = new Microsoft.AspNetCore.Routing.RouteData(), ActionDescriptor = new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor() }; var exceptionContext = new ExceptionContext(actionContext, new List <IFilterMetadata>() { filter }) { Exception = new ArgumentNullException("val", "argument is null") }; Assert.Null(exceptionContext.Result); filter.OnException(exceptionContext); var result = exceptionContext.Result as ObjectResult; Assert.NotNull(result); Assert.Equal("argument is null (Parameter 'val')", (string)result.Value); }
/// <summary> /// Добавить глобальный обработчик исключений в MVC pipeline. /// </summary> public static IGlobalExceptionFilterBuilder AddGlobalExceptionFilter(this IServiceCollection services) { var storage = new GlobalExceptionBuilderStorage(); services.AddSingleton(storage); return(new GlobalExceptionFilterBuilder(services, storage)); }
public GlobalExceptionFilter(ILoggerFactory?logger, GlobalExceptionBuilderStorage globalExceptionResult) { _globalExceptionResult = globalExceptionResult; if (logger is null) { throw new ArgumentNullException(nameof(logger)); } _logger = logger.CreateLogger <GlobalExceptionFilter>(); }
public void ShouldProperlyAddCustomExceptionFilters() { var storage = new GlobalExceptionBuilderStorage(); var builder = CreateBuilder(storage); Assert.Equal(0, storage.ExceptionHandlers.Count); builder.AddExceptionHandler <ArgumentNullException>(x => new ObjectResult(x.Message)); Assert.Equal(1, storage.ExceptionHandlers.Count); }
public void ShouldProperlyAddDefaultExceptionFilters() { var storage = new GlobalExceptionBuilderStorage(); var builder = CreateBuilder(storage); Assert.Equal(0, storage.ExceptionHandlers.Count); builder.AddDefaultExceptionHandlers(); Assert.Equal(3, storage.ExceptionHandlers.Count); }
GlobalExceptionFilterBuilder CreateBuilder(GlobalExceptionBuilderStorage builder) => new GlobalExceptionFilterBuilder(_services, builder);
GlobalExceptionFilter CreateFilter(GlobalExceptionBuilderStorage storage) => new GlobalExceptionFilter(new LoggerFactory(), storage);