Welcome to the eighteenth episode of my course “Becoming a software developer” in which we will finalize the basic CRUD for the Driver type, implement extension methods for the repository and build custom middleware in order to deal with exceptions.
All of the materials including videos and sample projects can be downloaded from here.
The source code repository is being hosted on GitHub.
Scope
- Extensions
- Middleware
Abstract
Extensions
I did write about extensions method already, but this time, I’d like to present how they can be used along with repository. Let’s consider the following scenario:
1 2 3 4 5 |
var driver = await _driverRepository.GetAsync(userId); if(driver == null) { throw new Exception($"Driver with user id: '{userId}' was not found."); } |
Quite often, we want to fetch e.g. driver within some application service and use it for some specific use case. Do we have to write the same code over and over again? Of course not, we could create a very simple extension methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public static class RepositoryExtensions { public static async Task<Driver> GetOrFailAsync(this IDriverRepository repository, Guid userId) { var driver = await repository.GetAsync(userId); if(driver == null) { throw new Exception($"Driver with user id: '{userId}' was not found."); } return driver; } public static async Task<User> GetOrFailAsync(this IUserRepository repository, Guid userId) { var user = await repository.GetAsync(userId); if(user == null) { throw new Exception($"User with id: '{userId}' was not found."); } return user; } } |
And then reduce the repetitive code to the single line:
1 |
var driver = await _driverRepository.GetOrFailAsync(userId); |
Middleware
ASP.NET Core framework is built around the middleware, which means that you can easily plug into the so-called pipeline and do pretty much whatever you want with the incoming HTTP request. This great feature can be used, for example for creating a global handler that will deal with the exceptions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
public class ExceptionHandlerMiddleware { private readonly RequestDelegate _next; public ExceptionHandlerMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch(Exception exception) { await HandleExceptionAsync(context, exception); } } private static Task HandleExceptionAsync(HttpContext context, Exception exception) { var errorCode = "error"; var statusCode = HttpStatusCode.BadRequest; var exceptionType = exception.GetType(); switch(exception) { case Exception e when exceptionType == typeof(UnauthorizedAccessException): statusCode = HttpStatusCode.Unauthorized; break; //TODO: Custom exception default: statusCode = HttpStatusCode.InternalServerError; break; } var response = new { code = errorCode, message = exception.Message }; var payload = JsonConvert.SerializeObject(response); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)statusCode; return context.Response.WriteAsync(payload); } } |
We can define a separate extension to make this integration look really cool
1 2 3 4 5 |
public static class Extensions { public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder builder) => builder.UseMiddleware(typeof(ExceptionHandlerMiddleware)); } |
And eventually use it within Startup class Configure() method like this:
1 |
app.UseExceptionHandler(); |
Next
In the next episode, we will deal with gracefully handling errors and extend the logging services by using NLog.
Pingback: Dew Drop - May 25, 2017 (#2487) - Morning Dew
After you buy Norton Antivirus visit norton.com/setup, sign in to norton account then enter norton product for Norton Setup or Install Norton … http://www.norton.com/setup. Protect your Pc/laptop and other devices with best Norton.com/setup Antivirus.
This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information.
norton.com/setup