Skip to content

Commit 3a7a14b

Browse files
committed
Created global filters for web apis
Fix bug BadRequest response after creating order
1 parent 4549980 commit 3a7a14b

22 files changed

Lines changed: 297 additions & 46 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
using Microsoft.AspNetCore.Http;
2+
using Microsoft.AspNetCore.Mvc;
3+
using System;
4+
using System.Collections.Generic;
5+
using System.Linq;
6+
using System.Threading.Tasks;
7+
8+
namespace Basket.API.Infrastructure.ActionResults
9+
{
10+
public class InternalServerErrorObjectResult : ObjectResult
11+
{
12+
public InternalServerErrorObjectResult(object error)
13+
: base(error)
14+
{
15+
StatusCode = StatusCodes.Status500InternalServerError;
16+
}
17+
}
18+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Threading.Tasks;
5+
6+
namespace Basket.API.Infrastructure.Exceptions
7+
{
8+
/// <summary>
9+
/// Exception type for app exceptions
10+
/// </summary>
11+
public class BasketDomainException : Exception
12+
{
13+
public BasketDomainException()
14+
{ }
15+
16+
public BasketDomainException(string message)
17+
: base(message)
18+
{ }
19+
20+
public BasketDomainException(string message, Exception innerException)
21+
: base(message, innerException)
22+
{ }
23+
}
24+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
using Basket.API.Infrastructure.ActionResults;
2+
using Basket.API.Infrastructure.Exceptions;
3+
using Microsoft.AspNetCore.Hosting;
4+
using Microsoft.AspNetCore.Mvc;
5+
using Microsoft.AspNetCore.Mvc.Filters;
6+
using Microsoft.Extensions.Logging;
7+
using System;
8+
using System.Collections.Generic;
9+
using System.Linq;
10+
using System.Net;
11+
using System.Threading.Tasks;
12+
13+
namespace Basket.API.Infrastructure.Filters
14+
{
15+
public class HttpGlobalExceptionFilter : IExceptionFilter
16+
{
17+
private readonly IHostingEnvironment env;
18+
private readonly ILogger<HttpGlobalExceptionFilter> logger;
19+
20+
public HttpGlobalExceptionFilter(IHostingEnvironment env, ILogger<HttpGlobalExceptionFilter> logger)
21+
{
22+
this.env = env;
23+
this.logger = logger;
24+
}
25+
26+
public void OnException(ExceptionContext context)
27+
{
28+
logger.LogError(new EventId(context.Exception.HResult),
29+
context.Exception,
30+
context.Exception.Message);
31+
32+
if (context.Exception.GetType() == typeof(BasketDomainException))
33+
{
34+
var json = new JsonErrorResponse
35+
{
36+
Messages = new[] { context.Exception.Message }
37+
};
38+
39+
context.Result = new BadRequestObjectResult(json);
40+
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
41+
}
42+
else
43+
{
44+
var json = new JsonErrorResponse
45+
{
46+
Messages = new[] { "An error ocurr.Try it again." }
47+
};
48+
49+
if (env.IsDevelopment())
50+
{
51+
json.DeveloperMeesage = context.Exception;
52+
}
53+
54+
context.Result = new InternalServerErrorObjectResult(json);
55+
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
56+
}
57+
context.ExceptionHandled = true;
58+
}
59+
60+
private class JsonErrorResponse
61+
{
62+
public string[] Messages { get; set; }
63+
64+
public object DeveloperMeesage { get; set; }
65+
}
66+
}
67+
}

src/Services/Basket/Basket.API/Startup.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
using Microsoft.eShopOnContainers.Services.Basket.API.IntegrationEvents.EventHandling;
1515
using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ;
1616
using System;
17+
using Basket.API.Infrastructure.Filters;
1718

1819
namespace Microsoft.eShopOnContainers.Services.Basket.API
1920
{
@@ -35,7 +36,11 @@ public Startup(IHostingEnvironment env)
3536
public void ConfigureServices(IServiceCollection services)
3637
{
3738
// Add framework services.
38-
services.AddMvc();
39+
services.AddMvc(options =>
40+
{
41+
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
42+
}).AddControllersAsServices();
43+
3944
services.Configure<BasketSettings>(Configuration);
4045

4146
//By connecting here we are making sure that our service
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
using Microsoft.AspNetCore.Http;
2+
using Microsoft.AspNetCore.Mvc;
3+
using System;
4+
using System.Collections.Generic;
5+
using System.Linq;
6+
using System.Threading.Tasks;
7+
8+
namespace Catalog.API.Infrastructure.ActionResults
9+
{
10+
public class InternalServerErrorObjectResult : ObjectResult
11+
{
12+
public InternalServerErrorObjectResult(object error)
13+
: base(error)
14+
{
15+
StatusCode = StatusCodes.Status500InternalServerError;
16+
}
17+
}
18+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Threading.Tasks;
5+
6+
namespace Catalog.API.Infrastructure.Exceptions
7+
{
8+
/// <summary>
9+
/// Exception type for app exceptions
10+
/// </summary>
11+
public class CatalogDomainException : Exception
12+
{
13+
public CatalogDomainException()
14+
{ }
15+
16+
public CatalogDomainException(string message)
17+
: base(message)
18+
{ }
19+
20+
public CatalogDomainException(string message, Exception innerException)
21+
: base(message, innerException)
22+
{ }
23+
}
24+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
using Catalog.API.Infrastructure.ActionResults;
2+
using Catalog.API.Infrastructure.Exceptions;
3+
using Microsoft.AspNetCore.Hosting;
4+
using Microsoft.AspNetCore.Mvc;
5+
using Microsoft.AspNetCore.Mvc.Filters;
6+
using Microsoft.Extensions.Logging;
7+
using System.Net;
8+
9+
namespace Catalog.API.Infrastructure.Filters
10+
{
11+
public class HttpGlobalExceptionFilter : IExceptionFilter
12+
{
13+
private readonly IHostingEnvironment env;
14+
private readonly ILogger<HttpGlobalExceptionFilter> logger;
15+
16+
public HttpGlobalExceptionFilter(IHostingEnvironment env, ILogger<HttpGlobalExceptionFilter> logger)
17+
{
18+
this.env = env;
19+
this.logger = logger;
20+
}
21+
22+
public void OnException(ExceptionContext context)
23+
{
24+
logger.LogError(new EventId(context.Exception.HResult),
25+
context.Exception,
26+
context.Exception.Message);
27+
28+
if (context.Exception.GetType() == typeof(CatalogDomainException))
29+
{
30+
var json = new JsonErrorResponse
31+
{
32+
Messages = new[] { context.Exception.Message }
33+
};
34+
35+
context.Result = new BadRequestObjectResult(json);
36+
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
37+
}
38+
else
39+
{
40+
var json = new JsonErrorResponse
41+
{
42+
Messages = new[] { "An error ocurr.Try it again." }
43+
};
44+
45+
if (env.IsDevelopment())
46+
{
47+
json.DeveloperMeesage = context.Exception;
48+
}
49+
50+
context.Result = new InternalServerErrorObjectResult(json);
51+
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
52+
}
53+
context.ExceptionHandled = true;
54+
}
55+
56+
private class JsonErrorResponse
57+
{
58+
public string[] Messages { get; set; }
59+
60+
public object DeveloperMeesage { get; set; }
61+
}
62+
}
63+
}

src/Services/Catalog/Catalog.API/Startup.cs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
namespace Microsoft.eShopOnContainers.Services.Catalog.API
22
{
3+
using global::Catalog.API.Infrastructure.Filters;
34
using global::Catalog.API.IntegrationEvents;
45
using Microsoft.AspNetCore.Builder;
56
using Microsoft.AspNetCore.Hosting;
@@ -41,6 +42,12 @@ public void ConfigureServices(IServiceCollection services)
4142
{
4243
var sqlConnection = new SqlConnection(Configuration["ConnectionString"]);
4344

45+
// Add framework services.
46+
services.AddMvc(options =>
47+
{
48+
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
49+
}).AddControllersAsServices();
50+
4451
services.AddDbContext<CatalogContext>(c =>
4552
{
4653
c.UseSqlServer(sqlConnection);
@@ -85,20 +92,13 @@ public void ConfigureServices(IServiceCollection services)
8592

8693
var serviceProvider = services.BuildServiceProvider();
8794
var configuration = serviceProvider.GetRequiredService<IOptionsSnapshot<Settings>>().Value;
88-
services.AddSingleton<IEventBus>(new EventBusRabbitMQ(configuration.EventBusConnection));
89-
90-
services.AddMvc();
95+
services.AddSingleton<IEventBus>(new EventBusRabbitMQ(configuration.EventBusConnection));
9196
}
9297

9398
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IntegrationEventLogContext integrationEventLogContext)
9499
{
95100
//Configure logs
96101

97-
if (env.IsDevelopment())
98-
{
99-
app.UseDeveloperExceptionPage();
100-
}
101-
102102
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
103103
loggerFactory.AddDebug();
104104

src/Services/Ordering/Ordering.API/Application/Commands/CreateOrderCommandHandler.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,8 @@ public async Task<bool> Handle(CreateOrderCommand message)
5151

5252
_orderRepository.Add(order);
5353

54-
var result = await _orderRepository.UnitOfWork
54+
return await _orderRepository.UnitOfWork
5555
.SaveEntitiesAsync();
56-
57-
return result > 0;
58-
5956
}
6057
}
6158
}

src/Services/Ordering/Ordering.API/Application/Commands/IdentifierCommandHandler.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,9 @@ public async Task<R> Handle(IdentifiedCommand<T, R> message)
4848
return CreateResultForDuplicateRequest();
4949
}
5050
else
51-
{
52-
await _requestManager.CreateRequestForCommandAsync<T>(message.Id);
51+
{
5352
var result = await _mediator.SendAsync(message.Command);
53+
await _requestManager.CreateRequestForCommandAsync<T>(message.Id);
5454
return result;
5555
}
5656
}

0 commit comments

Comments
 (0)