Add the following code to services where MVC service is registered.
services
.AddMvc(options=>options.Filters.Add(typeof(GlobalExceptionFilter)))
Example of global filter class (GlobalExceptionFilter) registered above with MVC
namespace TestCaseManagementTool.Infrastructure
{
public class GlobalExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
HandleException(context).GetAwaiter().GetResult();
context.ExceptionHandled = true;
}
private async Task HandleException(ExceptionContext context)
{
var contextt = context;
var code = (BaseException)context.Exception;
if(code.Code == 4001)
context.Result = new BadRequestObjectResult(JsonErrors.RequestedDataError);
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
}
}