DEV Community

Cover image for 𝗔𝗦𝗣.𝗡𝗘𝗧 𝗪𝗲𝗯 𝗔𝗣𝗜 𝗦𝗲𝗿𝗶𝗲𝘀 | 𝗚𝗹𝗼𝗯𝗮𝗹 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴 𝗶𝗻 𝗔𝗦𝗣.𝗡𝗘𝗧 𝗖𝗼𝗿𝗲 𝗪𝗲𝗯 𝗔𝗣𝗜
Syed Mohamed
Syed Mohamed

Posted on

𝗔𝗦𝗣.𝗡𝗘𝗧 𝗪𝗲𝗯 𝗔𝗣𝗜 𝗦𝗲𝗿𝗶𝗲𝘀 | 𝗚𝗹𝗼𝗯𝗮𝗹 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴 𝗶𝗻 𝗔𝗦𝗣.𝗡𝗘𝗧 𝗖𝗼𝗿𝗲 𝗪𝗲𝗯 𝗔𝗣𝗜

𝗣𝗮𝗿𝘁 𝟰 | 𝗔𝗦𝗣.𝗡𝗘𝗧 𝗪𝗲𝗯 𝗔𝗣𝗜 𝗦𝗲𝗿𝗶𝗲𝘀 | 𝗚𝗹𝗼𝗯𝗮𝗹 𝗘𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴 𝗶𝗻 𝗔𝗦𝗣.𝗡𝗘𝗧 𝗖𝗼𝗿𝗲 𝗪𝗲𝗯 𝗔𝗣𝗜
🚨 One unhandled exception can expose sensitive information and create an inconsistent experience for API consumers.

That is why every production-ready ASP.NET Core Web API needs Global Exception Handling.

Instead of adding 𝗿𝗲𝗽𝗲𝘁𝗶𝘁𝗶𝘃𝗲 try-catch 𝗯𝗹𝗼𝗰𝗸𝘀 inside every controller action, we can handle exceptions in one centralized place.

𝗜𝗻 .𝗡𝗘𝗧 𝟴+, 𝘁𝗵𝗲 𝗿𝗲𝗰𝗼𝗺𝗺𝗲𝗻𝗱𝗲𝗱 𝗮𝗽𝗽𝗿𝗼𝗮𝗰𝗵 𝗶𝘀:
✅ Implement IExceptionHandler
✅ Register it using AddExceptionHandler()
✅ Enable it using UseExceptionHandler()
✅ Return consistent ProblemDetails responses
✅ Log the complete exception internally

𝗛𝗼𝘄 𝗱𝗼𝗲𝘀 𝗶𝘁 𝘄𝗼𝗿𝗸?
1️⃣ The client sends an API request.
2️⃣ The request passes through the exception-handling middleware.
3️⃣ The controller calls the service and repository.
4️⃣ If an unhandled exception occurs, it travels back through the pipeline.
5️⃣ The global handler catches and logs it.
6️⃣ The exception is mapped to the correct HTTP status code.
7️⃣ A safe and consistent error response is returned.

𝗖𝗼𝗺𝗺𝗼𝗻 𝗲𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻 𝗺𝗮𝗽𝗽𝗶𝗻𝗴:
🔹 𝗜𝗻𝘃𝗮𝗹𝗶𝗱 𝗶𝗻𝗽𝘂𝘁 → 400 Bad Request
🔹 𝗔𝘂𝘁𝗵𝗲𝗻𝘁𝗶𝗰𝗮𝘁𝗶𝗼𝗻 𝗿𝗲𝗾𝘂𝗶𝗿𝗲𝗱 → 401 Unauthorized
🔹 𝗣𝗲𝗿𝗺𝗶𝘀𝘀𝗶𝗼𝗻 𝗱𝗲𝗻𝗶𝗲𝗱 → 403 Forbidden
🔹 𝗥𝗲𝘀𝗼𝘂𝗿𝗰𝗲 𝗻𝗼𝘁 𝗳𝗼𝘂𝗻𝗱 → 404 Not Found
🔹 𝗗𝘂𝗽𝗹𝗶𝗰𝗮𝘁𝗲 𝗼𝗿 𝗰𝗼𝗻𝗰𝘂𝗿𝗿𝗲𝗻𝗰𝘆 𝗰𝗼𝗻𝗳𝗹𝗶𝗰𝘁 → 409 Conflict
🔹 𝗕𝘂𝘀𝗶𝗻𝗲𝘀𝘀 𝘃𝗮𝗹𝗶𝗱𝗮𝘁𝗶𝗼𝗻 𝗳𝗮𝗶𝗹𝘂𝗿𝗲 → 422 Unprocessable Entity
🔹 𝗘𝘅𝘁𝗲𝗿𝗻𝗮𝗹 𝘀𝗲𝗿𝘃𝗶𝗰𝗲 𝘁𝗶𝗺𝗲𝗼𝘂𝘁 → 504 Gateway Timeout
🔹 𝗨𝗻𝗲𝘅𝗽𝗲𝗰𝘁𝗲𝗱 𝗲𝘅𝗰𝗲𝗽𝘁𝗶𝗼𝗻 → 500 Internal Server Error

A standard error response can include:
{
"title": "Resource not found",
"status": 404,
"detail": "Product with ID 100 was not found.",
"instance": "/api/products/100",
"traceId": "0HN7K2B8N98R2:00000001"
}
𝗧𝗵𝗲 traceId 𝗶𝘀 𝗲𝘀𝗽𝗲𝗰𝗶𝗮𝗹𝗹𝘆 𝘃𝗮𝗹𝘂𝗮𝗯𝗹𝗲 𝗶𝗻 𝗽𝗿𝗼𝗱𝘂𝗰𝘁𝗶𝗼𝗻. When a user reports an issue, the support team can use it to locate the related logs quickly.

𝗞𝗲𝘆 𝗽𝗼𝗶𝗻𝘁𝘀:
✅ Keep controllers clean and focused.
✅ Log complete exception details on the server.
✅ Return only safe messages to clients.
✅ Never expose stack traces, SQL queries or connection strings.
✅ Use custom exceptions for known business errors.
✅ Do not return 500 for every exception.
✅ Register the exception middleware early in the pipeline.
✅ Remember: normal validation errors and unknown-route 404 responses are not necessarily exceptions.

♻️ 𝗥𝗲𝗽𝗼𝘀𝘁 𝗶𝗳 𝘁𝗵𝗶𝘀 𝗵𝗲𝗹𝗽𝘀 𝗮𝗻𝗼𝘁𝗵𝗲𝗿 .𝗡𝗘𝗧 𝗱𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿.

𝗖𝗵𝗲𝗰𝗸 𝗼𝘂𝘁 𝘁𝗵𝗲 𝗹𝗶𝗻𝗸 𝗯𝗲𝗹𝗼𝘄 𝗳𝗼𝗿 𝗮 𝗱𝗲𝘁𝗮𝗶𝗹𝗲𝗱 𝗲𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 𝘄𝗶𝘁𝗵 𝗽𝗿𝗮𝗰𝘁𝗶𝗰𝗮𝗹 𝗲𝘅𝗮𝗺𝗽𝗹𝗲𝘀.👇
https://jntech.in/view/global-exception-handling-in-aspnet-core-web-api

Top comments (0)