In my application there are certain "friendly" messages that the services layer returns to me through a custom exception "LimsDataException" and that I want to show in the corresponding view. I solve them with a try/catch in the controller actions, generating a lot of repetitive code, could I solve it with an exception filter, with a custom middleware or in some other way?
[HttpPost]
public async Task<IActionResult> Create(PriorityVM vm)
{
if (ModelState.IsValid)
{
try
{
var priority = _mapper.Map<PriorityDto>(vm);
priority.Id = await _priorityService.Create(priority);
return RedirectToAction(nameof(Details), new { id = priority.Id });
}
catch (LimsDataException ex)
{
ModelState.AddModelError("", _dbLocalizer[ex.Message]);
}
}
return View(vm);
}
public class LimsDataExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
if (context.Exception is LimsDataException)
{
context.ModelState.AddModelError("", context.Exception.Message);
context.ExceptionHandled = true;
// Can I continue with the execution of the view? Do I need a Middleware?
}
}
}