Senior
How do you handle business errors and return correct HTTP codes to the client?
sobes.tech AI
Answer from AI
To handle business errors and return correct HTTP status codes in C#, custom exceptions and middleware or filters for centralized error handling are usually used.
Example approach:
- Create your own exception classes for different types of business errors:
public class NotFoundException : Exception {}
public class ValidationException : Exception {}
-
Throw these exceptions in controllers when necessary.
-
Use middleware to intercept exceptions and generate HTTP responses:
app.Use(async (context, next) => {
try
{
await next();
}
catch (NotFoundException)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
await context.Response.WriteAsync("Resource not found");
}
catch (ValidationException ex)
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync(ex.Message);
}
catch (Exception)
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
await context.Response.WriteAsync("Internal server error");
}
});
Thus, business logic is separated from HTTP processing, and the client receives understandable and correct response codes depending on the situation.