Status Codes & Errors
Advanced
20 min read
Lesson 8 of 10
The Traffic Light Story: When you drive, traffic lights tell you what to do. Green means go (Success). Red means stop (Error). Yellow means caution (Redirect). APIs use Status Codes exactly like traffic lights to tell the client what happened!
Connecting to C#
When you write a C# method, it usually returns a value. But what if it fails? You might throw an exception: throw new Exception("Not found");
In REST APIs, we don't just throw exceptions. We return a specific HTTP Status Code so the client knows exactly what went wrong without crashing.
Common Status Codes (Cheat Sheet)
- 200 OK: The request was successful.
- 201 Created: A new resource was successfully created (used after POST).
- 400 Bad Request: The client sent invalid data.
- 401 Unauthorized: You need to log in.
- 404 Not Found: The URL or data doesn't exist.
- 500 Internal Server Error: The server crashed (a bug in your C# code).
Example: Returning Status Codes in ASP.NET Core
ASP.NET Core provides built-in helper methods to return these codes:
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
var user = _database.Users.Find(id);
if (user == null)
{
// Returns HTTP 404
return NotFound("User does not exist");
}
if (id < 0)
{
// Returns HTTP 400
return BadRequest("ID cannot be negative");
}
// Returns HTTP 200 with the user object
return Ok(user);
}
Handling Server Errors (Try-Catch)
[HttpPost]
public IActionResult CreateUser(User user)
{
try
{
_database.Users.Add(user);
_database.SaveChanges();
return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
}
catch (Exception ex)
{
// Log the error, and return 500
return StatusCode(500, "An internal server error occurred.");
}
}