1

In my service code, i am validating my objects and if it fails, it throws a ValidationException (using FluentValidation), this in turns throws an exception with error code 500.

Without going through all my methods and adding a try..catch, is it possible to add something in the mvc pipeline that will see if a ValidationException has been thrown, and if so return a BadRequest with the Message of the ValidationException in?

If i were to update all my methods, it would look something like this

try
{
    await _service.AddAsync(entity);

    // return created response
    return Created(_httpContextAccessor.HttpContext.Request.GetDisplayUrl(), _mapper.Map<DatasheetModel>(entity));
}
catch (ValidationException e)
{
    return BadRequest(e.Message);
}

Is this possible, recommended, or should i just update all my methods as above?

Gillardo
  • 9,518
  • 18
  • 73
  • 141
  • @David - That question is referencing Web API 2 which is pre ASP.NET Core. This question is referencing MVC 6 which is ASP.NET Core. So the two are totally unrelated. – Clint B May 19 '16 at 12:09
  • @David - ASP.NET Core is a total rewrite of ASP.NET and does away with System.Web.dll. Since everything pre ASP.NET Core is based on System.Web.dll, they don't work anywhere close to the same way. – Clint B May 19 '16 at 12:31
  • The idea of the middleware for exception handling is the same, period http://stackoverflow.com/a/34312016/2410379 – David Pine May 19 '16 at 12:36
  • @David - The idea might be the same but the implementation is different. The solution in the link you just posted uses IExceptionHandler which comes from System.Web.dll. That does not exist in ASP.NET Core. – Clint B May 19 '16 at 12:44
  • @ClintB that is why I posted and answer detailing the ASP.NET Core implementation. I do realize that it's a rewrite, and it does not rely on `System.Web.dll`. Thank you – David Pine May 19 '16 at 12:47

2 Answers2

0

You do not have to put a try/catch everywhere. You can create exception handling middleware and inject it in the Http pipeline. Middleware is one of the main concepts of ASP.NET Core. I have an RC1 project posted on GitHub that demonstrates how to create middleware in three easy steps. You can download it here. The ReadMe file will explain how to search the project for relevant areas of the code.

I've also posted a project that demonstrates how to develop custom exception handler middleware. You can download that project here. Again the ReadMe file will explain how to search the project for relevant areas of the code.

Clint B
  • 4,610
  • 2
  • 18
  • 22
0

The awesome thing about ASP.NET Core is that they have taken the concept of middleware to the next level. This can be achieved as you desire by simply creating and implementing some custom middleware. Middleware is able to see every request and corresponding response and act on it.

public class ValidationExceptionMiddleware  
{
    private readonly RequestDelegate _next;

    public ValidationExceptionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)  
    {
        // Handle exceptions and propagate appropriate response
        await _next.Invoke(context);
    }
}

Once you have your middleware authored add it in the Startup.Configure method:

public void Configure(IApplicationBuilder app, 
                      IHostingEnvironment env, 
                      ILoggerFactory loggerFactory)  
{
    // Omitted for brevity...
    app.UseMiddleware<ValidationExceptionMiddleware>();
}

There are also exception filters, but that doesn't allow you to interact with the request and response pipeline.

David Pine
  • 23,787
  • 10
  • 79
  • 107