-1

How to handle the exception in MVC in such a way that control moves to a particular point when exception occurs at any place of the code? Please explain with example

Black Pearl
  • 79
  • 1
  • 2
  • 9
  • Does this answer your question? [Error Handling in ASP.NET MVC](https://stackoverflow.com/questions/812235/error-handling-in-asp-net-mvc) – H.Sarxha May 07 '21 at 14:46

3 Answers3

0

use try-catch

try{
----code----
}
catch(exception ex)
{
---code after exception occurs---
}

here,ex catches the exception and you can check for the reason exception occured as well

0

There are many ways to do that it depends on where you want your control to be

most basic place will be to use

Try-catch-finally.

Next is to use the BaseController and using the OnException Method there

Another approach will be to use the GlobalException handling using filters which are provided by MVC

next approach could be to use the Application_Error in the global.asax.cs and this will be a single place where we can write our own exception logic

0

This is one example how you can do it. ExceptionMiddleware is responsible for dealing with exceptions.
Of course you need to add it in Configure method of Startup.cs class. Something like this:

app.UseMiddleware<ExceptionMiddleware>();

 public class ExceptionMiddleware
    {
        private readonly RequestDelegate next;
        private readonly ILogger<ExceptionMiddleware> logger;
        private readonly IHostEnvironment env;
        public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger, IHostEnvironment env)
        {
            this.env = env;
            this.logger = logger;
            this.next = next;


        }

        public async Task InvokeAsync(HttpContext context)
        {

            try 
            {
                await next(context);
            }
            catch(Exception ex) 
            {
              logger.LogError(ex,ex.Message);
              context.Response.ContentType = "application/json";
              context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
              var response = env.IsDevelopment() 
              ? new ApiException((int)HttpStatusCode.InternalServerError, ex.Message, ex.StackTrace.ToString())
                    : new ApiException((int)HttpStatusCode.InternalServerError);

                   var options = new JsonSerializerOptions{PropertyNamingPolicy = JsonNamingPolicy.CamelCase};

                   var json = JsonSerializer.Serialize(response, options);

                   await context.Response.WriteAsync(json);






            }
        }
    }
 public class ApiResponse
    {
        public ApiResponse(int statusCode, string message = null)
        {
            StatusCode = statusCode;
            Message = message ?? GetDefaultMessageForStatusCode(statusCode);
        }

        public int StatusCode { get; set; }
        public string Message { get; set; }

        private string GetDefaultMessageForStatusCode(int statusCode)
        {
            return statusCode switch
            {
                400 => "A bad request, you have made",
                401 => "Authorized, you are not",
                404 => "Resource found, it was not",
                500 => "Errors are the path to the dark side. Errors lead to anger.  Anger leads to hate.  Hate leads to career change",
                _ => null
            };
        }
    }

public class ApiException : ApiResponse
    {
        public ApiException(int statusCode, string message = null, string details = null) : base(statusCode, message)
        {
            Details = details;
        }

        public string Details { get; set; }
    }

mspaic96
  • 91
  • 1
  • 3