Search Sreeni's Insights

Filter by content type
crafting April 28, 2015 7 min read

Exception handling best practices in .NET

Exception handling practices for .NET, ASP.NET MVC, and Web API covering swallowed exceptions, stack traces, specific catches, and global error handling.

Share:

Exception handling best practices in .NET

Exceptions are part of every application. The database is going down, the network call is timing out, the user is sending the invalid input. The question is not whether the exceptions will happen, the question is how we handle them when they happen. Poor exception handling either hides the real problem (swallowed exceptions) or exposes the internal details to the clients (stack trace in the API response). Both are dangerous. In this article, we are going to see the common mistakes and the best practices for exception handling in .NET, ASP.NET MVC and Web API.

TL;DR Summary

  • Exceptions are for exceptional situations, don’t use them for normal flow control.
  • Don’t swallow exceptions with empty catch blocks.
  • Catch only when you can handle it, otherwise let it bubble up.
  • Use throw; to re-throw, not throw ex;, otherwise the stack trace is lost.
  • Catch specific exceptions, not the base Exception, except at the application boundary.
  • Have one global exception handler which logs and returns a friendly response.
  • Don’t send the stack trace to the clients, it is a security risk.
  • Always log with enough context to diagnose the issue.

Challenges

Swallowed exceptions

The most dangerous pattern is the empty catch block. The application continues as if nothing happened, the data is partially saved and the user sees a success message. Days later, the customer reports wrong numbers and there is no log, no trace, nothing. The Mean Time To Detect (MTTD) and Mean Time To Resolve (MTTR) are going up, hence it will have direct impact on the SLA.

Lost stack trace

When the exception is re-thrown with throw ex;, the stack trace is reset to the current line. The log shows the error is from the catch block, not from the actual line where it happened. The developer has to guess the root cause.

Stack trace exposed to clients

When the unhandled exception reaches the client with full details, it exposes the class names, file paths, SQL queries and sometimes even connection strings. It is a free map of our system for the attackers. And also, it is a bad experience for the user to see a yellow screen of death.

Try-catch everywhere

Some code bases have try-catch in every method, logging the same exception five times on the way up. The logs are full of noise, and it is hard to find the real issue.

What is an Exception?

An exception is an error condition or unexpected behaviour which occurs during the execution of a program, and which interrupts the normal flow.

In simple terms, it is the program saying “I cannot continue with what you asked me to do”. In .NET, every exception is an object derived from System.Exception and carries the message, the type and the stack trace.

Think about a fire alarm in a building. When it rings, you don’t switch it off and continue working (swallowing). You also don’t announce the details of the electrical wiring to the visitors (stack trace to clients). You follow a clear procedure, people are moved to safety and the fire team investigates the root cause.

Why proper exception handling is important?

In order to detect the issues early, to diagnose them quickly and to protect the system and users from internal details, we should have a consistent exception handling strategy in every application. It reduces the MTTR, improves the security and gives a better experience to the users.

Best Practices

Let us discuss the best practices one by one with examples.

Don’t swallow exceptions

// Bad
try
{
    _fundRepository.Save(fund);
}
catch (Exception)
{
}

// Good - let it bubble up, or log and re-throw if you must add context
try
{
    _fundRepository.Save(fund);
}
catch (SqlException ex)
{
    _logger.Error(ex, "Failed to save fund {0}", fund.Id);
    throw;
}

If you really need to ignore a specific exception, catch that specific type and add a comment explaining why.

Use throw; and not throw ex;

// Bad - stack trace starts here
catch (Exception ex)
{
    throw ex;
}

// Good - original stack trace is preserved
catch (Exception)
{
    throw;
}

When you want to add more context, wrap the original exception as the inner exception.

catch (SqlException ex)
{
    throw new FundRepositoryException("Failed to load fund " + fundId, ex);
}

Catch specific exceptions

Catch only the exceptions you expect and know how to handle. Catching Exception everywhere hides the bugs like NullReferenceException which should be fixed, not handled.

try
{
    var price = _pricingClient.GetPrice(fundId);
}
catch (TimeoutException)
{
    return _priceCache.GetLastKnownPrice(fundId);
}

Don’t use exceptions for flow control

Exceptions are expensive and they make the code harder to follow. Use checks and return values for expected situations.

// Bad
try
{
    var units = int.Parse(input);
}
catch (FormatException)
{
    units = 0;
}

// Good
int units;
if (!int.TryParse(input, out units))
{
    units = 0;
}

Validate early (fail fast)

Validate the arguments at the beginning of the public methods and throw the right exception with a clear message.

public void Redeem(int fundId, decimal units)
{
    if (units <= 0)
        throw new ArgumentOutOfRangeException("units", "Units must be greater than zero.");
    // ...
}

Use using for disposable resources

using makes sure the resources are released even when an exception is thrown, no need of try-finally.

using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, connection))
{
    connection.Open();
    // ...
}

Create custom exceptions only when it adds value

Create a custom exception when the caller needs to handle that case differently, i.e. FundNotFoundException which maps to HTTP 404. Don’t create custom exceptions for every class.

[Serializable]
public class FundNotFoundException : Exception
{
    public FundNotFoundException(int fundId)
        : base("Fund " + fundId + " was not found.")
    {
    }
}

Global exception handling

Most of the exceptions should be handled at one place, at the boundary of the application. It logs the error once and converts it into a friendly response.

ASP.NET MVC

Use the HandleErrorAttribute (registered by default in FilterConfig) with custom errors, and log in Application_Error.

<system.web>
  <customErrors mode="RemoteOnly" defaultRedirect="~/Error" />
</system.web>
protected void Application_Error()
{
    var exception = Server.GetLastError();
    Logger.Error(exception, "Unhandled exception");
}

Note: Always use mode="RemoteOnly" or mode="On" in production. mode="Off" shows the full error details to everyone.

ASP.NET Web API

Web API 2 has IExceptionLogger and IExceptionHandler for global handling. Use the logger to log all unhandled exceptions and the handler to return a consistent error response without internal details.

public class GlobalExceptionLogger : ExceptionLogger
{
    public override void Log(ExceptionLoggerContext context)
    {
        Logger.Error(context.Exception, "Unhandled API exception");
    }
}

public class GlobalExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        var correlationId = Guid.NewGuid().ToString();

        context.Result = new ResponseMessageResult(
            context.Request.CreateResponse(HttpStatusCode.InternalServerError, new
            {
                message = "An unexpected error occurred. Please contact support with the reference id.",
                referenceId = correlationId
            }));
    }
}

Register them in WebApiConfig.

config.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger());
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.LocalOnly;

The client gets a reference id, which the support team can use to find the full error in the logs. The client never sees the stack trace.

Info: In the real implementation, log the same correlation id together with the exception, otherwise the reference id is not useful for the support team.

Logging

Exception handling without logging is half done. Here are some few guidelines,

  • Log the full exception (ex.ToString()), including inner exceptions and stack trace, in the server logs.
  • Add the context, i.e. fund id, user id, request URL, correlation id.
  • Log once, at the place where the exception is handled, not at every layer.
  • Don’t log the passwords, tokens and personal data.
  • Use a logging framework like log4net, NLog or Serilog, and send the logs to a central place, so the operations team can search them.

Don’ts

  • Don’t write empty catch blocks.
  • Don’t use throw ex;.
  • Don’t catch Exception in the business logic.
  • Don’t use exceptions for normal flow control.
  • Don’t send the stack trace or internal messages to the clients.
  • Don’t log the same exception at every layer.

Wrap up

In this article, we have looked at the common mistakes in exception handling, the best practices like not swallowing exceptions, preserving the stack trace and catching specific exceptions, and how to set up global exception handling in ASP.NET MVC and Web API without exposing internal details. I appreciate your time and efforts to read this article. In the next article, I will walk you through what is engineering practices and why do we need them.

Related Posts