@manhng

Welcome to my blog!

C# Catch Exception

May 7, 2018 22:44

C# Catch Exception (edit)

https://stackify.com/csharp-catch-all-exceptions/

.NET Framework Exception Events

static void Main(string[] args)
{
  Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
  AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}

static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
  // Log the exception, display it, etc
  Debug.WriteLine(e.Exception.Message);
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
  // Log the exception, display it, etc
  Debug.WriteLine((e.ExceptionObject as Exception).Message);
}

ASP.NET Core Error Handling

public class ErrorHandlingFilter : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {
        var exception = context.Exception;
        //log your exception here

        context.ExceptionHandled = true; //optional 
    }
}

//in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc(options =>
    {
        options.Filters.Add(new ErrorHandlingFilter());
    });
}

Web API Error Handling

public class UnhandledExceptionLogger : ExceptionLogger  
{
    public override void Log(ExceptionLoggerContext context)
    {
        var log = context.Exception.ToString();
        //Write the exception to your logs
    }
}

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        //Register it here
        config.Services.Replace(typeof(IExceptionLogger), new UnhandledExceptionLogger());

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

MVC Error Handling

MVC Error Handling - 1) Must Have: Global Error Page With Web.Config <customErrors>

<system.web>
    <customErrors mode="On" defaultRedirect="~/ErrorHandler/Index">
        <error statusCode="404" redirect="~/ErrorHandler/NotFound"/>
    </customErrors>
<system.web/>

MVC Error Handling - 2) Use MVC HandlerErrorAttribute to Customize Responses

[HandleError(ExceptionType = typeof(SqlException), View = "SqlExceptionView")]
public string GetClientInfo(string username)
{
	return "true";
}

MVC Error Handling - 3) Use MVC Controller OnException to Customize Responses

public class UserMvcController : Controller
{
   protected override void OnException(ExceptionContext filterContext)
   {
      filterContext.ExceptionHandled = true;

	  //Log the error!!
      _Logger.Error(filterContext.Exception);

      //Redirect or return a view, but not both.
      filterContext.Result = RedirectToAction("Index", "ErrorHandler");
      // OR 
      filterContext.Result = new ViewResult
      {
         ViewName = "~/Views/ErrorHandler/Index.cshtml"
      };
   }
}

MVC Error Handling - 4) Use HttpApplication Application_Error as Global Exception Handler

public class MvcApplication : System.Web.HttpApplication
{
   protected void Application_Start()
   {
      AreaRegistration.RegisterAllAreas();
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
      RouteConfig.RegisterRoutes(RouteTable.Routes);
      BundleConfig.RegisterBundles(BundleTable.Bundles);
   }

   protected void Application_Error()
   {
      var ex = Server.GetLastError();
      //log the error!
      _Logger.Error(ex);
   }
}

ASP.NET Exception Handling

//Global.asax
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Error(object sender, EventArgs e)
    {
        Exception exception = Server.GetLastError();
        if (exception != null)
        {
            //log the error
        }
    }

    protected void Application_Start()
    {
        //may have some MVC registration stuff here or other code
    }
}

Catching "First Chance Exceptions"

AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
{
	Debug.WriteLine(eventArgs.Exception.ToString());
};

AppDomain.CurrentDomain.FirstChanceException

https://malvinly.com/2012/05/25/net-4-0-and-first-chance-exceptions/

https://malvinly.com/2012/04/08/executing-code-in-a-new-application-domain/

static void Main(string[] args)
{
    AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
    {
        Console.WriteLine("First chance exception: " + eventArgs.Exception.Message);
    };
 
    try
    {
        Console.WriteLine("Before exception.");
        throw new Exception("Some error.");
    }
    catch
    {
        Console.WriteLine("Handled.");
    }
}
static void Main(string[] args)
{
    AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
    {
        try
        {
            throw new Exception();
        }
        catch
        {
        }
    };
 
    try
    {
        throw new Exception();
    }
    catch
    {
    }
}
static void Main(string[] args)
{
    AppDomain.CurrentDomain.FirstChanceException += (sender, eventArgs) =>
    {
        StackFrame[] frames = new StackTrace(1).GetFrames();
        MethodBase currentMethod = MethodBase.GetCurrentMethod();
 
        if (frames != null && frames.Any(x => x.GetMethod() == currentMethod))
            return;
 
        throw new Exception();
    };
 
    throw new Exception();
}

Categories

Recent posts