Error Handling and Logging in ASP.NET Core

Ibrahim Jaber
3 min readOct 20, 2023

You may be new to this, but by the end of this blog, you’ll have the skills to tackle errors and keep track of your application’s behavior like a pro. Buckle up; we’re diving in!

Let’s Set the Stage with a Fun Problem

Imagine you’re the brains behind a futuristic restaurant, “TechCafe,” where robots prepare and serve food. Your business is booming, and the robots are working non-stop. However, they occasionally encounter errors like running out of ingredients or crashing into each other while serving.

Your task is to ensure these errors are handled gracefully, so your customers don’t end up with a robot chef on their lap! But how can you achieve this without getting lost in a sea of error messages?

Error Handling: The Lifesaver

ASP.NET Core provides a robust error handling mechanism that can save the day. You’ll use it to catch errors and provide informative responses to your customers.

Step 1: Configure Error Handling

First, let’s set up error handling in your ASP.NET Core project. Open your Startup.cs file and add the following code to the Configure method:

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

In this code, we configure the application to show detailed error pages during development but provide a user-friendly error page in production.

Step 2: Handle Errors Gracefully

Now, let’s handle a specific error scenario. Robots in your TechCafe sometimes run out of coffee beans. When this happens, you don’t want your customers to see a generic error page; you want a message like, “Our robot barista is taking a coffee break.”

[Route("order")]
public async Task<IActionResult> OrderCoffee()
{
try
{
// Your coffee-making code here
// ...
if (coffeeMachine.IsEmpty())
{
throw new CoffeeMachineException("Our robot barista is taking a coffee break.");
}
// ...
return View();
}
catch (CoffeeMachineException ex)
{
// Log the error
_logger.LogError(ex, "Out of coffee beans");
// Return a friendly error message
return View("CoffeeBreak");
}
}

In this code, we catch a specific exception, CoffeeMachineException, log the error, and return a custom error page with a friendly message.

Logging: The Watchful Eye

Now that your error handling is in place, let’s set up logging to keep an eye on what’s happening in your TechCafe.

Step 3: Configure Logging

In your Startup.cs, configure your logger in the ConfigureServices method:

services.AddLogging(builder =>
{
builder.AddConsole();
builder.AddDebug();
});

This code configures your logger to output logs to the console and debug window. You can also configure other destinations like files or external services.

Step 4: Start Logging

In your code, you can now use the logger to record events, errors, and information:

public async Task<IActionResult> ServeFood()
{
// Your code to serve food
// ...
_logger.LogInformation("Robot served food to table {tableNumber}");
// ...
}

You can log different log levels, including information, warning, and error. These logs provide valuable insights into what’s happening in your application.

Conclusion

Error handling and logging in ASP.NET Core are essential tools to ensure your application runs smoothly. They’re your safety net, catching errors and keeping you informed about what’s happening under the hood.

In the world of “TechCafe,” robots can now serve food without crashing into each other, and customers know that a coffee break means just that. With these skills, you’re equipped to create applications that handle errors gracefully and provide valuable insights to keep everything running smoothly.

So, go ahead, implement error handling and logging in your ASP.NET Core project, and navigate the complex world of software development with confidence. Happy coding, fellow developer! 🚀🤖📝

--

--

Ibrahim Jaber

Software developer | Programming and Blockchain enthusiast | If you'd like to buy me coffee: https://ko-fi.com/ibrahimjaber