public ExceptionHandler(IExceptionMapper mapper, ILogger <ExceptionHandler> logger, IOptions <MvcNewtonsoftJsonOptions> options, IOptions <Options.AppSettings> appSettings)
 {
     _mapper      = mapper ?? throw new ArgumentNullException(nameof(mapper));
     _logger      = logger ?? throw new ArgumentNullException(nameof(logger));
     _options     = options ?? throw new ArgumentNullException(nameof(options));
     _appSettings = appSettings.Value ?? throw new ArgumentNullException(nameof(appSettings));
 }
Ejemplo n.º 2
0
 public DbContextBase(
     string nameOrConnectionString,
     IExceptionMapper exceptionMapper = null)
     : base(nameOrConnectionString)
 {
     SetExceptionMapper(exceptionMapper);
 }
Ejemplo n.º 3
0
 public ExceptionHandler(IExceptionMapper mapper, ILogger <ExceptionHandler> logger,
                         IOptions <MvcJsonOptions> options)
 {
     _mapper  = mapper;
     _logger  = logger;
     _options = options;
 }
Ejemplo n.º 4
0
 public DbContextBase(
     string nameOrConnectionString,
     IExceptionMapper exceptionMapper = null)
     : base(nameOrConnectionString)
 {
     SetExceptionMapper(exceptionMapper);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ExceptionMappingErrorHandler"/> class.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        public ExceptionMappingErrorHandler(ExceptionHandlingAttribute attribute)
        {
            handlingAttribute = attribute;

            if (handlingAttribute.ExceptionMapper != null)
                exceptionMapper = (IExceptionMapper)Activator.CreateInstance(handlingAttribute.ExceptionMapper);
        }
Ejemplo n.º 6
0
 public DbContextBase(
     string nameOrConnectionString,
     DbCompiledModel model,
     IExceptionMapper exceptionMapper = null)
     : base(nameOrConnectionString, model)
 {
     SetExceptionMapper(exceptionMapper);
 }
Ejemplo n.º 7
0
 public DbContextBase(
     string nameOrConnectionString,
     DbCompiledModel model,
     IExceptionMapper exceptionMapper = null)
     : base(nameOrConnectionString, model)
 {
     SetExceptionMapper(exceptionMapper);
 }
Ejemplo n.º 8
0
 public DbContextBase(
     DbConnection existingConnection,
     bool contextOwnsConnection,
     IExceptionMapper exceptionMapper = null)
     : base(existingConnection, contextOwnsConnection)
 {
     SetExceptionMapper(exceptionMapper);
 }
Ejemplo n.º 9
0
 public DbContextBase(
     DbConnection existingConnection,
     bool contextOwnsConnection,
     IExceptionMapper exceptionMapper = null)
     : base(existingConnection, contextOwnsConnection)
 {
     SetExceptionMapper(exceptionMapper);
 }
Ejemplo n.º 10
0
 public DbContextBase(
     ObjectContext objectContext,
     bool dbContextOwnsObjectContext,
     IExceptionMapper exceptionMapper = null)
     : base(objectContext, dbContextOwnsObjectContext)
 {
     SetExceptionMapper(exceptionMapper);
 }
Ejemplo n.º 11
0
 public DbContextBase(
     ObjectContext objectContext,
     bool dbContextOwnsObjectContext,
     IExceptionMapper exceptionMapper = null)
     : base(objectContext, dbContextOwnsObjectContext)
 {
     SetExceptionMapper(exceptionMapper);
 }
Ejemplo n.º 12
0
 protected DbContextBase(
     IExceptionMapper exceptionMapper = null,
     IEntityAdder entityAdder         = null,
     IEntityUpdater entityUpdater     = null,
     IEntityDeleter entityDeleter     = null,
     IEntityDetacher entityDetacher   = null)
     : base()
 {
     Init(exceptionMapper, entityAdder, entityUpdater, entityDeleter, entityDetacher);
 }
 /// <summary>
 ///     Create new instance.
 /// </summary>
 public ExceptionHandlerMiddleware(RequestDelegate next,
                                   IExceptionMapper <TException> mapper,
                                   IOptions <ExceptionHandlerOptions> options,
                                   ILogger <ExceptionHandlerMiddleware <TException> > logger)
 {
     _next    = next ?? throw new ArgumentNullException(nameof(next));
     _mapper  = mapper ?? throw new ArgumentNullException(nameof(mapper));
     _options = options?.Value ?? throw new ArgumentNullException(nameof(options));
     _logger  = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Ejemplo n.º 14
0
 protected DbContextBase(
     IExceptionMapper exceptionMapper = null,
     IEntityAdder entityAdder = null,
     IEntityUpdater entityUpdater = null,
     IEntityDeleter entityDeleter = null,
     IEntityDetacher entityDetacher = null)
     : base()
 {
     Init(exceptionMapper, entityAdder, entityUpdater, entityDeleter, entityDetacher);
 }
 public ApiExceptionFilter(IExceptionMapper mapper, IHostingEnvironment env,
                           ILogger <ApiExceptionFilter> logger)
 {
     _mapper     = mapper;
     _env        = env;
     _logger     = logger;
     _serializer = new JsonSerializer
     {
         ContractResolver = new CamelCasePropertyNamesContractResolver()
     };
 }
Ejemplo n.º 16
0
 public DbContextBase(
     string nameOrConnectionString,
     IExceptionMapper exceptionMapper = null,
     IEntityAdder entityAdder         = null,
     IEntityUpdater entityUpdater     = null,
     IEntityDeleter entityDeleter     = null,
     IEntityDetacher entityDetacher   = null)
     : base(nameOrConnectionString)
 {
     Init(exceptionMapper, entityAdder, entityUpdater, entityDeleter, entityDetacher);
 }
Ejemplo n.º 17
0
 public DbContextBase(
     string nameOrConnectionString,
     IExceptionMapper exceptionMapper = null,
     IEntityAdder entityAdder = null,
     IEntityUpdater entityUpdater = null,
     IEntityDeleter entityDeleter = null,
     IEntityDetacher entityDetacher = null)
     : base(nameOrConnectionString)
 {
     Init(exceptionMapper, entityAdder, entityUpdater, entityDeleter, entityDetacher);
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Executes registered exception mapping schemes and returns an <see cref="ExceptionHandlingResult"/>.
        /// </summary>
        /// <param name="mapper">The exception mapper.</param>
        /// <param name="exception">The exception to handle.</param>
        public static Task <ExceptionHandlingResult> MapAsync(
            this IExceptionMapper mapper,
            Exception exception)
        {
            if (mapper == null)
            {
                throw new ArgumentNullException(nameof(mapper));
            }

            return(mapper.MapAsync(exception, null));
        }
Ejemplo n.º 19
0
 public DbContextBase(
     DbConnection existingConnection,
     bool contextOwnsConnection,
     IExceptionMapper exceptionMapper = null,
     IEntityAdder entityAdder         = null,
     IEntityUpdater entityUpdater     = null,
     IEntityDeleter entityDeleter     = null,
     IEntityDetacher entityDetacher   = null)
     : base(existingConnection, contextOwnsConnection)
 {
     Init(exceptionMapper, entityAdder, entityUpdater, entityDeleter, entityDetacher);
 }
Ejemplo n.º 20
0
 public DbContextBase(
     ObjectContext objectContext,
     bool dbContextOwnsObjectContext,
     IExceptionMapper exceptionMapper = null,
     IEntityAdder entityAdder = null,
     IEntityUpdater entityUpdater = null,
     IEntityDeleter entityDeleter = null,
     IEntityDetacher entityDetacher = null)
     : base(objectContext, dbContextOwnsObjectContext)
 {
     Init(exceptionMapper, entityAdder, entityUpdater, entityDeleter, entityDetacher);
 }
Ejemplo n.º 21
0
 public DbContextBase(
     DbConnection existingConnection,
     bool contextOwnsConnection,
     IExceptionMapper exceptionMapper = null,
     IEntityAdder entityAdder = null,
     IEntityUpdater entityUpdater = null,
     IEntityDeleter entityDeleter = null,
     IEntityDetacher entityDetacher = null)
     : base(existingConnection, contextOwnsConnection)
 {
     Init(exceptionMapper, entityAdder, entityUpdater, entityDeleter, entityDetacher);
 }
Ejemplo n.º 22
0
 public DbContextBase(
     ObjectContext objectContext,
     bool dbContextOwnsObjectContext,
     IExceptionMapper exceptionMapper = null,
     IEntityAdder entityAdder         = null,
     IEntityUpdater entityUpdater     = null,
     IEntityDeleter entityDeleter     = null,
     IEntityDetacher entityDetacher   = null)
     : base(objectContext, dbContextOwnsObjectContext)
 {
     Init(exceptionMapper, entityAdder, entityUpdater, entityDeleter, entityDetacher);
 }
 internal ApiExceptionHandler(IExceptionMapper mapper, IHostingEnvironment env,
                              ILogger <ApiExceptionHandler> logger, Action <Exception>[] exceptionListeners)
 {
     _mapper             = mapper;
     _env                = env;
     _logger             = logger;
     _exceptionListeners = exceptionListeners;
     _serializer         = new JsonSerializer
     {
         ContractResolver = new CamelCasePropertyNamesContractResolver()
     };
 }
Ejemplo n.º 24
0
 private void Init(
     IExceptionMapper exceptionMapper,
     IEntityAdder entityAdder,
     IEntityUpdater entityUpdater,
     IEntityDeleter entityDeleter,
     IEntityDetacher entityDetacher)
 {
     SetExceptionMapper(exceptionMapper);
     SetEntityAdder(entityAdder);
     SetEntityUpdater(entityUpdater);
     SetEntityDeleter(entityDeleter);
     SetEntityDetacher(entityDetacher);
 }
 public ApiExceptionFilterImpl(IExceptionMapper mapper, IHostEnvironment env,
                               ILogger <ApiExceptionFilter> logger, Action <Exception>[] exceptionListeners)
 {
     _mapper             = mapper;
     _env                = env;
     _logger             = logger;
     _exceptionListeners = exceptionListeners;
     _serializerOptions  = new JsonSerializerOptions
     {
         PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
         IgnoreNullValues     = true
     };
 }
Ejemplo n.º 26
0
        public ExceptionHandler(IExceptionMapper mapper, ILogger <ExceptionHandler> logger, IOptions <MvcJsonOptions> options, IOptions <ApiExtensionOptions> apiExtensionOptions)
        {
            if (mapper == null)
            {
                throw new ArgumentNullException(nameof(mapper));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            _mapper              = mapper;
            _logger              = logger;
            _options             = options;
            _apiExtensionOptions = apiExtensionOptions;
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Handles exception using registered schemes and executes the handling result.
        /// </summary>
        /// <param name="mapper">The exception mapper.</param>
        /// <param name="exception">The exception to handle.</param>
        /// <param name="context">The data context shared by all components used by the mapper.</param>
        public static async Task <object?> MapExceptionAsync(
            this IExceptionMapper mapper,
            Exception exception,
            ExceptionMappingContext?context = null)
        {
            if (mapper == null)
            {
                throw new ArgumentNullException(nameof(mapper));
            }

            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            var result = await mapper.MapAsync(exception, context);

            return(result.GetResult());
        }
Ejemplo n.º 28
0
        /// <inheritdoc/>
        public OpenApiResult GetResponse(Exception exception, OpenApiOperation operation)
        {
            Type exceptionType = exception.GetType();
            OpenApiMappedException mappedException = this.GetMappedException(operation, exceptionType);

            IExceptionMapper mapper = this.GetExceptionMapperFor(mappedException, exception, operation);

            if (mapper == null)
            {
                string operationId = operation.GetOperationId();
                this.logger.LogError(
                    "Unmapped exception thrown by [{operationId}]: [{exception}]",
                    operationId,
                    exception);
                throw new OpenApiServiceMismatchException($"Operation {operationId} has thrown an exception of type {exception.GetType().FullName}. You should either handle this in your service, or add an exception mapping defining which status code this exception corresponds to.");
            }

            return(mapper.MapException(operation.Responses, exception, mappedException?.StatusCode));
        }
        /// <summary>
        /// Adds exception mapping middleware to re-execute request in an alternative request pipeline.
        /// </summary>
        /// <param name="app">The application builder.</param>
        /// <param name="mapper">The exception mapper to use.</param>
        public static IApplicationBuilder UseEndpointExceptionMapping(
            this IApplicationBuilder app,
            IExceptionMapper mapper)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (mapper == null)
            {
                throw new ArgumentNullException(nameof(mapper));
            }

            var options = new EndpointExceptionMappingOptions
            {
                Mapper             = mapper,
                ApplicationBuilder = app.New()
            };

            return(app.UseEndpointExceptionMapping(options));
        }
 public static IExceptionMapper RegisterMapper(this IExceptionMapper mapper)
 {
     return(mapper
            .AddMap <IValidationException, ValidationException>());
 }
 public ExceptionStatusCodeDecoratorMiddleware(RequestDelegate next, IExceptionMapper mapper, ILogger <ExceptionStatusCodeDecoratorMiddleware> logger)
 {
     _next   = next;
     _mapper = mapper;
     _logger = logger;
 }
Ejemplo n.º 32
0
 private void SetExceptionMapper(IExceptionMapper exceptionMapper)
 {
     _exceptionMapper = exceptionMapper ?? new NullExceptionMapper();
 }
 public void Add(IExceptionMapper ex)
 {
     _children.Add(ex);
 }
Ejemplo n.º 34
0
 protected virtual void SetExceptionMapper(IExceptionMapper exceptionMapper)
 {
     _exceptionMapper = exceptionMapper ?? new NullExceptionMapper();
 }
Ejemplo n.º 35
0
 private void Init(
     IExceptionMapper exceptionMapper,
     IEntityAdder entityAdder,
     IEntityUpdater entityUpdater,
     IEntityDeleter entityDeleter,
     IEntityDetacher entityDetacher)
 {
     SetExceptionMapper(exceptionMapper);
     SetEntityAdder(entityAdder);
     SetEntityUpdater(entityUpdater);
     SetEntityDeleter(entityDeleter);
     SetEntityDetacher(entityDetacher);
 }
Ejemplo n.º 36
0
 private void SetExceptionMapper(IExceptionMapper exceptionMapper)
 {
     if (exceptionMapper != null)
         _exceptionMapper = exceptionMapper;
 }
Ejemplo n.º 37
0
 protected ControllerBase(IServiceCollection service, ILogger <Controller> logger)
 {
     this.Logger      = logger;
     this.Service     = service;
     _exceptionMapper = service.BuildServiceProvider().GetService <IExceptionMapper>();
 }
Ejemplo n.º 38
0
 protected virtual void SetExceptionMapper(IExceptionMapper exceptionMapper)
 {
     _exceptionMapper = exceptionMapper ?? new NullExceptionMapper();
 }
Ejemplo n.º 39
0
 public DbContextBase(
     IExceptionMapper exceptionMapper)
     : base()
 {
     SetExceptionMapper(exceptionMapper);
 }
Ejemplo n.º 40
0
 public DbContextBase(
     IExceptionMapper exceptionMapper)
     : base()
 {
     SetExceptionMapper(exceptionMapper);
 }
Ejemplo n.º 41
0
 private void SetExceptionMapper(IExceptionMapper exceptionMapper)
 {
     _exceptionMapper = exceptionMapper ?? new NullExceptionMapper();
 }
Ejemplo n.º 42
0
 public ExceptionHandlingDynamicProxy(IExceptionMapper exceptionMapper)
 {
     _exceptionMapper = exceptionMapper;
 }
 public void Add(IExceptionMapper ex)
 {
     _children.Add(ex);
 }
Ejemplo n.º 44
0
 protected DbContextBase()
     : base()
 {
     _exceptionMapper = new NullExceptionMapper();
 }
        internal static ApiError Build <TCategoryName>(HttpContext context, Exception ex, IExceptionMapper mapper,
                                                       ILogger <TCategoryName> logger, bool isDevelopment, Action <Exception>[] exceptionListeners)
        {
            //Execute custom exception handlers first.
            foreach (var customExceptionListener in exceptionListeners)
            {
                try
                {
                    customExceptionListener.Invoke(ex);
                }
                catch (Exception e)
                {
                    logger.LogWarning(e, "Custom exception listener {exceptionListener} threw an exception.", customExceptionListener.GetType().ToString());
                }
            }

            context.Response.ContentType = "application/json";

            HttpStatusCode statusCode;

            (int errorCode, string error)errorObject;
            object developerContext = null;
            object exceptionContext = new {};

            switch (ex)
            {
            case BaseApiException baseApiException:
                try
                {
                    if (mapper.Options.RespondWithDeveloperContext)
                    {
                        developerContext = baseApiException.DeveloperContext;
                    }
                    exceptionContext            = baseApiException.Context;
                    errorObject                 = mapper.GetError(baseApiException);
                    statusCode                  = mapper.GetExceptionHandlerReturnCode(baseApiException);
                    context.Response.StatusCode = (int)statusCode;
                    logger.LogInformation(ex,
                                          "Mapped BaseApiException of type {exceptionType} caught by ApiExceptionHandler. Will return with {statusCodeInt} {statusCodeString}. Unexpected: {unexpected}",
                                          ex.GetType(), (int)statusCode, statusCode.ToString(), false);
                }
                catch (ArgumentException)
                {
                    goto default;
                }

                break;

            case OperationCanceledException _:
                errorObject = (-1, "Frogvall.AspNetCore.ExceptionHandling.OperationCanceled");
                statusCode  = HttpStatusCode.InternalServerError;
                context.Response.StatusCode = (int)statusCode;
                logger.LogWarning(ex,
                                  "OperationCanceledException exception caught by ApiExceptionHandler. Will return with {statusCodeInt} {statusCodeString}. Unexpected: {unexpected}",
                                  (int)statusCode, statusCode.ToString(), true);
                break;

            default:
                errorObject = (-1, "Frogvall.AspNetCore.ExceptionHandling.InternalServerError");
                statusCode  = HttpStatusCode.InternalServerError;
                context.Response.StatusCode = (int)statusCode;
                logger.LogError(ex,
                                "Unhandled exception of type {exceptionType} caught by ApiExceptionHandler. Will return with {statusCodeInt} {statusCodeString}. Unexpected: {unexpected}",
                                ex.GetType(), (int)statusCode, statusCode.ToString(), true);
                break;
            }

            var error = new ApiError(mapper.Options.ServiceName)
            {
                CorrelationId    = context.TraceIdentifier,
                Context          = exceptionContext,
                DeveloperContext = developerContext,
                ErrorCode        = errorObject.errorCode,
                Error            = errorObject.error
            };

            if (isDevelopment)
            {
                error.Message         = ex.Message;
                error.DetailedMessage = ex.ToString();
            }
            else
            {
                error.Message = Regex.Replace(statusCode.ToString(), "[a-z][A-Z]",
                                              m => m.Value[0] + " " + char.ToLower(m.Value[1]));
                error.DetailedMessage = ex.Message;
            }

            return(error);
        }
        internal static ApiError Build <TCategoryName>(HttpContext context, Exception ex, IExceptionMapper mapper,
                                                       ILogger <TCategoryName> logger, bool isDevelopment)
        {
            context.Response.ContentType = "application/json";

            HttpStatusCode statusCode;
            int            errorCode;
            object         developerContext = null;

            switch (ex)
            {
            case BaseApiException _:
                try
                {
                    developerContext            = (ex as BaseApiException)?.DeveloperContext;
                    errorCode                   = mapper.GetErrorCode(ex as BaseApiException);
                    statusCode                  = mapper.GetExceptionHandlerReturnCode(ex as BaseApiException);
                    context.Response.StatusCode = (int)statusCode;
                    logger.LogInformation(ex,
                                          "Mapped BaseApiException of type {exceptionType} caught by ApiExceptionHandler. Will return with {statusCodeInt} {statusCodeString}. Unexpected: {unexpected}",
                                          ex.GetType(), (int)statusCode, statusCode.ToString(), false);
                }
                catch (ArgumentException)
                {
                    goto default;
                }

                break;

            case ApiException _:
                errorCode  = -2;
                statusCode = (ex as ApiException).StatusCode;
                context.Response.StatusCode = (int)statusCode;
                logger.LogInformation(ex,
                                      "ApiException caught by ApiExceptionHandler with  {statusCodeInt} {statusCodeString}. Unexpected: {unexpected}", (int)statusCode, statusCode.ToString(), false);
                break;

            default:
                errorCode  = -1;
                statusCode = HttpStatusCode.InternalServerError;
                context.Response.StatusCode = (int)statusCode;
                logger.LogError(ex,
                                "Unhandled exception of type {exceptionType} caught by ApiExceptionHandler. Will return with {statusCodeInt} {statusCodeString}. Unexpected: {unexpected}",
                                ex.GetType(), (int)statusCode, statusCode.ToString(), true);
                break;
            }

            var error = new ApiError(mapper.Options.ServiceName)
            {
                CorrelationId    = context.TraceIdentifier,
                DeveloperContext = developerContext,
                ErrorCode        = errorCode,
            };

            if (isDevelopment)
            {
                error.Message         = ex.Message;
                error.DetailedMessage = ex.ToAsyncString();
            }
            else
            {
                error.Message = Regex.Replace(statusCode.ToString(), "[a-z][A-Z]",
                                              m => m.Value[0] + " " + char.ToLower(m.Value[1]));
                error.DetailedMessage = ex.Message;
            }

            return(error);
        }