Search code examples
exception.net-coremodel-view-controllermiddlewareasp.net-core-5.0

create a Custom Exception Handler Middleware generating response based on client request


How to create a Custom Exception Handler Middleware. This middleware should generate a custom response based on the Calling Client. If the client is requesting via AJAX then the response should be a JSON Response describing the Error otherwise Redirect the client to Error page.

Controller code

public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

middleware code

public class ErrorHandlerMiddleware
    {
        private readonly RequestDelegate _next;

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

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception error)
            {
                var response = context.Response;
                var customError = new CustomError();

                switch (error)
                {
                    case AppException e:
                        // custom application error
                        customError.StatusCode = (int)HttpStatusCode.BadRequest; 
                        break;
                    case KeyNotFoundException e:
                        // not found error
                        customError.StatusCode = (int)HttpStatusCode.NotFound;
                        break;
                    default:
                        // unhandled error
                        customError.StatusCode = (int)HttpStatusCode.InternalServerError;
                        break;
                }
                customError.ErrorMessage = error?.Message;

                if (context.Request.ContentType == "application/json;")
                {
                    var result = JsonSerializer.Serialize(customError);
                    await response.WriteAsync(result);
                }
                else
                {
                    context.Response.Redirect("/Errors/CustomError");
                }
            }
        }

Custom Error class code

public class CustomError
    {
        public int StatusCode { get; set; }
        public string ErrorMessage { get; set; }
    }

Error View model

public class ErrorViewModel
    {
        public string RequestId { get; set; }

        public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
    }

Solution

  • you could add the code in your startup class:

    app.UseStatusCodePagesWithReExecute("/errors/{0}");
    

    add a controller(In my case I tested with HttpContext.Request.Headers["Content-Type"] ,it should be context.Request.ContentType == "application/json;" for MVC project ):

    public class ErrorsController : Controller
        {
            [Route("errors/{statusCode}")]
            public IActionResult CustomError(int statusCode)
            {
                if (HttpContext.Request.Headers["Content-Type"] == "application/json")
                {
                    
                    var cuserr = new CustomError() { ErrorMessage = "err", StatusCode = statusCode };
                    return new JsonResult(cuserr);
                }
                else
                {
                    if (statusCode == 404)
                    {
                        return View("~/Views/Errors/404.cshtml");
                    }
                    return View("~/Views/Errors/500.cshtml");
                }
                
            }
        }
    

    and the views:

    enter image description here

    The result:

    enter image description here

    for more details,you could read the offcial document: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-6.0