Error handling is a critical part of building reliable and user-friendly applications. In the .NET world, developers often debate whether to use exceptions or the result pattern for handling errors. This article explores both approaches, their advantages and drawbacks, and presents a hybrid method that combines the best of both worlds.
The Challenge of Error Handling
Every developer needs to manage errors in their applications to prevent crashes and provide meaningful feedback to users. However, choosing the right strategy for error handling can be tricky. Should you stick with exceptions, which are straightforward and integrated into the language, or should you opt for the result pattern, which offers more explicit control? Let’s explore these options.
Using Exceptions: The Traditional Way
Advantages of Exceptions
- Simplicity: Throwing and catching exceptions is easy and built into the .NET framework.
- Separation of Concerns: Exceptions allow error handling to be separated from business logic, which can make the code cleaner.
- Robust Framework Support: The .NET framework has extensive support for exceptions, including various built-in exception types and the familiar try-catch-finally blocks.
Disadvantages of Exceptions
- Performance Cost: Exceptions can be expensive in terms of performance, especially if they are used for regular control flow.
- Hidden Control Flow: Exceptions can obscure the normal flow of the program, making the code harder to read and understand.
- Risk of Unhandled Exceptions: If exceptions are not properly managed, they can propagate and cause the application to crash.
Example of Exceptions
Here’s a simple example of using exceptions in a service class:
public class SampleService
{
public string GetData(bool shouldFail)
{
if (shouldFail)
{
throw new InvalidOperationException("Data not found.");
}
return "Data fetched successfully.";
}
}
The Result Pattern: A More Explicit Approach
Advantages of the Result Pattern
- Explicit Handling: The result pattern makes error handling explicit, which can make the code more understandable and maintainable.
- Better Testability: It’s easier to write tests for both success and failure cases without relying on exceptions.
- Avoids Uncaught Exceptions: By using results instead of exceptions, you reduce the risk of unhandled exceptions causing crashes.
Disadvantages of the Result Pattern
- Verbosity: The result pattern can make the code more verbose because you need to check the result of every operation.
- Mixed Concerns: Business logic and error handling can become intertwined, which can make the code less readable.
Example of the Result Pattern
Here’s how you can use the result pattern in a service class:
public class Result<T>
{
public bool IsSuccess { get; }
public T Value { get; }
public string Error { get; }
private Result(bool isSuccess, T value, string error)
{
IsSuccess = isSuccess;
Value = value;
Error = error;
}
public static Result<T> Success(T value) => new Result<T>(true, value, null);
public static Result<T> Failure(string error) => new Result<T>(false, default(T), error);
}
public class SampleService
{
public Result<string> GetData(bool shouldFail)
{
if (shouldFail)
{
return Result<string>.Failure("An error occurred while fetching data.");
}
return Result<string>.Success("Data fetched successfully.");
}
}
Introducing the Hybrid Approach
To get the best of both approaches, we can use a hybrid method. This involves using the result pattern for expected business logic failures and exceptions for unexpected, exceptional cases. We’ll also centralize error handling using a base controller and a custom exception handler using IExceptionHandler
introduced in .NET 8.
Enhanced Error Class
First, we’ll enhance the Error
class to include status codes for more descriptive errors.
public class Error
{
public string Message { get; }
public int StatusCode { get; }
private Error(string message, int statusCode)
{
Message = message;
StatusCode = statusCode;
}
public static Error NotFound(string message) => new Error(message, 404);
public static Error BadRequest(string message) => new Error(message, 400);
public static Error Unauthorized(string message) => new Error(message, 401);
public static Error Forbidden(string message) => new Error(message, 403);
public static Error InternalServerError(string message) => new Error(message, 500);
}
Updated Result Class for the Hybrid Approach
We’ll update the Result
class to work with the enhanced Error
class.
public class Result<T>
{
public bool IsSuccess { get; }
public T Value { get; }
public Error Error { get; }
private Result(bool isSuccess, T value, Error error)
{
IsSuccess = isSuccess;
Value = value;
Error = error;
}
public static Result<T> Success(T value) => new Result<T>(true, value, null);
public static Result<T> Failure(Error error) => new Result<T>(false, default(T), error);
}
BaseApiController
Next, we’ll create a BaseApiController
class to handle the result processing and generate appropriate responses.
[ApiController]
public abstract class BaseApiController : ControllerBase
{
protected IActionResult Handle<T>(Result<T> result)
{
if (result.IsSuccess)
{
return Ok(result.Value);
}
var problemDetails = new ProblemDetails
{
Title = "An error occurred",
Status = result.Error.StatusCode,
Detail = result.Error.Message,
Instance = HttpContext.Request.Path
};
return StatusCode(result.Error.StatusCode, problemDetails);
}
}
SampleService
Here’s our updated service layer using the enhanced error handling.
public class SampleService
{
public Result<string> GetData(bool shouldFail)
{
if (shouldFail)
{
return Result<string>.Failure(Error.NotFound("Data not found."));
}
return Result<string>.Success("Data fetched successfully.");
}
}
SampleController
Inherit from BaseApiController
and use the Handle
method to process results.
[Route("api/[controller]")]
public class SampleController : BaseApiController
{
private readonly SampleService _service;
public SampleController(SampleService service)
{
_service = service;
}
[HttpGet("{shouldFail}")]
public IActionResult GetData(bool shouldFail)
{
var result = _service.GetData(shouldFail);
return Handle(result);
}
}
Custom Exception Handler
Define a custom exception handler to format error responses using ProblemDetails
.
public class CustomExceptionHandler : IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception,
CancellationToken cancellationToken)
{
var problemDetails = new ProblemDetails
{
Title = "An error occurred while processing your request.",
Status = (int)HttpStatusCode.InternalServerError,
Detail = exception.Message,
Instance = httpContext.Request.Path
};
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken: cancellationToken);
return true;
}
}
Registering Services and Exception Handler
Ensure your services and the custom exception handler are registered in the dependency injection container inside Program.cs
file.
var builder = WebApplication.CreateBuilder(args);
// Register sample service and custom exception handler
builder.Services.AddScoped<SampleService>();
builder.Services.AddExceptionHandler<CustomExceptionHandler>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Conclusion
Both exceptions and the result pattern have their place in .NET error handling. Exceptions offer a simple and integrated way to handle unexpected errors, while the result pattern provides more explicit and testable error management. By combining these approaches in a hybrid method, you can create robust, maintainable, and user-friendly applications. This hybrid approach uses the result pattern for expected errors and exceptions for truly exceptional cases, ensuring that your application handles errors gracefully and consistently.
Top comments (0)