Learning Error Handling in Controllers — Simple, Smart & Fun!
👋 Introduction
Welcome, my friend! 😊
Today we’re diving into one of the most important skills in ASP.NET Core — Error Handling in Controllers.
Every application, no matter how perfect, will face errors.
So instead of fearing them, you will learn how to control them, catch them, and return safe messages to the user.
Once you understand Error Handling in Controllers, you will feel more confident because your apps will stop crashing and start responding gracefully ✨
Let’s begin this fun learning journey 🚀
📚 What You Are Going to Learn in This Lesson
✔️ What Error Handling in Controllers means
✔️ Why errors happen inside controllers
✔️ How to use try–catch properly
✔️ How to return friendly error messages
✔️ How to avoid crashes using input validation
✔️ A beginner-friendly code example
✔️ A practical real-world scenario
🧠 Understanding the Basics of Error Handling in Controllers
When your app receives a wrong input, or the database fails, or some unexpected issue happens — your controller is the first place to crash.
That’s why Error Handling in Controllers is so important.
To protect your app, you use:
try { }catch (Exception ex) { }- Return a safe response instead of breaking your entire app.
This makes your code reliable, stable, and user-friendly.
💻 Code Example (with Explanation & Output)
Here is a simple action method showing Error Handling in Controllers:
using Microsoft.AspNetCore.Mvc;
public class MathController : Controller
{
public IActionResult Divide(int a, int b)
{
try
{
if (b == 0)
throw new Exception("You cannot divide by zero!");
int result = a / b;
return Json(new { Status = "Success", Result = result });
}
catch (Exception ex)
{
return Json(new { Status = "Error", Message = ex.Message });
}
}
}
📤 Expected Output
🟩 Valid Input
URL: /Math/Divide?a=10&b=2
Output:
{
"Status": "Success",
"Result": 5
}
🟥 Error Input (division by zero)
URL: /Math/Divide?a=10&b=0
Output:
{
"Status": "Error",
"Message": "You cannot divide by zero!"
}
This is exactly how Error Handling in Controllers keeps your app safe and clean.
🏠 Real-Life Scenario (Very Practical)
Imagine you are working on a banking application.
Users are trying to transfer money, and suddenly your controller receives a negative or invalid amount.
Without Error Handling in Controllers, the whole application would crash and show a scary error screen ❌
But with a simple try-catch:
- You detect the invalid value
- You show a safe message
- The system remains stable
- Users trust your app more
This is why learning Error Handling in Controllers is super important.
More Programming Examples
Here are 4 super easy coding examples of Error Handling in Controllers, each with clear explanations and expected outputs.
These examples are beginner-friendly and help you understand error handling in different situatio
✅ Example 1: Handling Missing Query Parameters
public IActionResult SayHello(string name)
{
try
{
if (string.IsNullOrWhiteSpace(name))
throw new Exception("Name is required!");
return Content($"Hello, {name}!");
}
catch (Exception ex)
{
return Content($"Error: {ex.Message}");
}
}
✔️ Explanation
- If
nameis missing, empty, or null, we throw an error. - The catch block returns a friendly message instead of breaking the app.
📤 Output
URL: /Home/SayHello?name=Rahul
Hello, Rahul!
URL: /Home/SayHello
Error: Name is required!
✅ Example 2: Handling Invalid Number Input
public IActionResult SquareNumber(string number)
{
try
{
int n = int.Parse(number); // may throw error
return Json(new { Result = n * n });
}
catch (Exception ex)
{
return Json(new { Error = ex.Message });
}
}
✔️ Explanation
- If the user enters a non-numeric value,
int.Parsewill throw an error. - The catch block returns a clean JSON error message.
📤 Output
URL: /Math/SquareNumber?number=5
{ "Result": 25 }URL: /Math/SquareNumber?number=hello
{ "Error": "Input string was not in a correct format." } ✅ Example 3: Handling Database-like Errors (Simulated)
public IActionResult GetUser(int id)
{
try
{
if (id <= 0)
throw new Exception("Invalid user ID!");
// Simulating: database returns null
string user = null;
if (user == null)
throw new Exception("User not found!");
return Content($"User: {user}");
}
catch (Exception ex)
{
return Content($"Error: {ex.Message}");
}
}
✔️ Explanation
ID must be positive.
We simulate a “user not found” condition.
All errors are caught safely.
📤 Output
URL: /User/GetUser?id=0
Error: Invalid user ID!
URL: /User/GetUser?id=10
Error: User not found!
✅ Example 4: Handling Model Binding Errors
public IActionResult SaveProduct(Product model)
{
try
{
if (!ModelState.IsValid)
throw new Exception("Invalid product data!");
return Json(new { Status = "Saved", model.Name });
}
catch (Exception ex)
{
return Json(new { Status = "Error", Message = ex.Message });
}
}
public class Product
{
public string Name { get; set; }
public int Price { get; set; }
}
✔️ Explanation
If the form sends wrong values (like text instead of number), ModelState becomes invalid.
The error is caught and returned as a simple JSON message.
📤 Output
Valid Data:
{
"Status": "Saved",
"name": "Mobile"
}Invalid Data Example (Price = “ABC”):
{
"Status": "Error",
"Message": "Invalid product data!"
} 👌 Final Thoughts
Mistakes happen.
But professional developers handle them smartly.
When you learn Error Handling in Controllers, you take your first big step toward building stable, bug-free applications.
You are learning amazingly fast — keep going! ✨
👉 Next what?
In the next chapter you will learn “Views in ASP.Net Core”
Excited for the next step?
Let’s keep the momentum going 🚀
