How should a global exception handler differentiate between exceptions meant for client-facing details versus exceptions that should always show a generic message?
Short answer
A common pattern defines a custom base exception class (like ApiException with a public Message and StatusCode meant for client display) that business logic throws for expected, user-facing error conditions, while any exception NOT inheriting from this base type is treated as an…
Advertisement
AModel answer
A common pattern defines a custom base exception class (like ApiException with a public Message and StatusCode meant for client display) that business logic throws for expected, user-facing error conditions, while any exception NOT inheriting from this base type is treated as an internal error given only a generic message -- this explicit opt-in design prevents accidentally leaking internal exception details for exception types never designed to be shown to end users.
public class ApiException(string message, int statusCode = 400) : Exception(message) {
public int StatusCode { get; } = statusCode;
}
var (status, message) = exception is ApiException apiEx
? (apiEx.StatusCode, apiEx.Message)
: (500, "An unexpected error occurred");Real-world example
A checkout flow throws a custom InsufficientStockException : ApiException with a clear customer-facing message, while an unrelated database timeout exception (not inheriting ApiException) is automatically shown only as a generic 'something went wrong' message.
Likely follow-ups
- How do you ensure developers consistently use the ApiException base class for new user-facing errors?
- What's the risk of accidentally making ApiException too broadly applicable?
Related topics