Prácticas recomendadas para el manejo de excepciones en C #

Como parte del inminente inicio del curso "C # Developer. Professional" , hemos preparado una traducción del material para usted. También invitamos a todos a una lección de demostración gratuita "Contenedores DI para C #" . En esta lección: 1) Comprendemos qué es el principio DI y por qué es necesario; 2) Aprenda a aplicar DI sin usar contenedores; 3) Consideremos dos contenedores DI populares para C #: Windsor y Autofac, analicemos sus pros y contras; 4) Aprenderemos a registrar dependencias, gestionar su ciclo de vida, aplicar la inyección de dependencias.


















. - ( , ). C#.





. , « » . . , try/catch



:





try
{
    try
    {
        //  - ,     SpecificException

    }
    catch (SpecificException specificException)
    {
        log.LogError(specificException, "Specific error");
    }
    

    //  - 
}
catch (Exception exception)
{
    log.LogError(exception, "General erro");
}
      
      



, , , try/catch



, . SpecificException



catch



, . :





catch (SpecificException specificException)
{
    // ...
    throw specificException;
}
      
      



:





catch (SpecificException specificException)
{
    // ...
    throw;
}
      
      



, SpecificException



, , . .





. Exception, Data. . , , . elmah.io



Data Data.





Data /:





var exception = new Exception("En error happened");
exception.Data.Add("user", Thread.CurrentPrincipal.Identity.Name);
throw exception;
      
      



user



, .





, . try/catch



:





try
{
    service.SomeCall();
}
catch (Exception e)
{
    e.Data.Add("user", Thread.CurrentPrincipal.Identity.Name);
    throw;
}
      
      



, SomeCall



, . throw



catch



.





, - , :





try
{
    File.WriteAllText(path, contents);
}
catch (Exception e)
{
    logger.Error(e);
}
      
      



Exception



. , .NET, , . — , .





, :





try
{
    File.WriteAllText(path, contents);
}
catch (ArgumentException ae)
{
    Message.Show("Invalid path");
}
catch (DirectoryNotFoundException dnfe)
{
    Message.Show("Directory not found");
}
catch (Exception e)
{
    var supportId = Guid.NewGuid();
    e.Data.Add("Support id", supportId);
    logger.Error(e);
    Message.Show($"Please contact support with id: {supportId}");
}
      
      



ArgumentException



DirectoryNotFoundException



Exception



, . , . Exception



support id



, ( , ) .





, , , , — . :





, . , , .





NullReferenceException



. null



, null



. , NullReferenceException



:





Address a = null;
var city = a.City;
      
      



a . , , a .





city



, , null-condition



:





Address a = null;
var city = a?.City;
      
      



?



a C# , null



. city



null



.





— . FormatException



:





var i = int.Parse("invalid");
      
      



invalid



. try/catch



, int



, , , 1000 :





if (int.TryParse("invalid", out int i))
{
}
      
      



, invalid



int



, TryParse



true



i



. .





, Java- ( .NET -). . , - Java, .NET C#. , , . , , Data:





public class MyVerySpecializedException : Exception
{
    public MyVerySpecializedException() : base() {}
    public MyVerySpecializedException(string message) : base(message) {}
    public MyVerySpecializedException(string message, Exception inner) : base(message, inner) {}
    
    public int Status { get; set; }
}
      
      



MyVerySpecializedException



(, , :D) , . , Status . :





try
{
    service.SomeCall();
}
catch (MyVerySpecializedException e) when (e.Status == 500)
{
    // Do something specific for Status 500
}
catch (MyVerySpecializedException ex)
{
    // Do something general
}
      
      



when



, MyVerySpecializedException



, Status 500. catch MyVerySpecializedException



.





. :





try
{
    service.SomeCall();
}
catch
{
    // 
}
      
      



, — , . , , , . .





, NLog Serilog. - ASP.NET (Core), elmah.io .






"C# Developer. Professional".





«DI- C#».








All Articles