Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

Design an exception hierarchy for a shared platform library used by many services, including how it maps to HTTP errors and error codes.

Keep the hierarchy small: one base PlatformException and a handful of subclasses named by how a caller should handle them, such as NotFound, Conflict, Validation and Unavailable. Each exception carries a stable machine-readable error code and structured context fields, says explicitly whether it is retryable, and never puts secrets or personal data in its message. One shared @RestControllerAdvice maps the categories to HTTP status codes and RFC 9457 problem details, so every service answers errors the same way.

Why this question is asked

A shared platform library is used by dozens or hundreds of services for years, so its exception types become part of everyone's code: handlers catch them, dashboards count them, clients parse the responses they produce. A good design makes errors predictable across the whole company; a poor one leads to each service inventing its own mapping and clients writing special cases per service. Interviewers ask this at senior level to see whether we design for the people who handle errors, not just the people who throw them. In this answer, we will decide what the hierarchy should be organized around, design the base class, map it to HTTP in one place, make retryability explicit, and cover the rules that keep it safe and stable over time.

1What Should the Hierarchy Be Organized Around?

The first decision is the axis of the hierarchy. A common mistake is to organize by where the error came from: DatabaseException, KafkaException, PaymentClientException. That tells the reader the source, but a caller rarely cares about the source. What a caller needs to know is what to do: tell the user the thing does not exist, ask them to fix their input, retry later, or give up.

So we organize by handling category. NotFoundException means the target does not exist. ConflictException means the request clashes with the current state, such as a duplicate or a version mismatch. ValidationException means the input is wrong and retrying the same request will never work. UnavailableException means a dependency is down or overloaded and a retry later may succeed. A few more may earn a place, such as Forbidden, but we keep the list short, perhaps five to seven types. Every new subclass is another case every handler must think about.

The source of the failure still matters for debugging, and it is not lost: it lives in the cause chain and in context fields, not in the class name.

2Designing the Base Class

The base class carries what every handler needs: a stable error code, a category, structured context, and a retryable flag. The message stays for humans.

Java
public abstract class PlatformException extends RuntimeException {
private final String code; // stable, documented: "ORDER_NOT_FOUND"
private final Map<String, Object> context; // safe, structured values: orderId, field names
protected PlatformException(String code, String message, Map<String, Object> context, Throwable cause) {
super(message, cause);
this.code = Objects.requireNonNull(code);
this.context = Map.copyOf(context);
}
public String code() { return code; }
public Map<String, Object> context() { return context; }
public abstract Category category(); // NOT_FOUND, CONFLICT, VALIDATION, UNAVAILABLE, INTERNAL
public boolean retryable() { return category() == Category.UNAVAILABLE; }
}
public class NotFoundException extends PlatformException {
public NotFoundException(String code, String message, Map<String, Object> context) {
super(code, message, context, null);
}
public Category category() { return Category.NOT_FOUND; }
}
throw new NotFoundException("ORDER_NOT_FOUND", "Order not found", Map.of("orderId", "A-17"));

The error code is the contract. Clients and dashboards match on ORDER_NOT_FOUND, never on the message text, so we can improve the wording of a message without breaking anyone. Codes are documented in one registry, never reused for a different meaning, and namespaced by domain when many teams add them.

Notice that the context is a map of simple values, copied so it cannot change later. Handlers can put those values into the response and into structured logs, which is far more useful than parsing them out of a message. The constructor always accepts a cause, so a service that translates a lower-level exception keeps the original.

3Mapping Categories to HTTP in One Place

The mapping from category to HTTP status belongs in the library, not in each service. Spring Framework 6 supports RFC 9457 problem details, a standard JSON format for HTTP errors with fields such as type, title, status and detail plus any extensions, through the ProblemDetail class. The library ships one @RestControllerAdvice that every service gets automatically through a starter.

Java
@RestControllerAdvice
class PlatformExceptionHandler {
@ExceptionHandler(PlatformException.class)
ResponseEntity<ProblemDetail> handle(PlatformException ex, HttpServletRequest request) {
HttpStatus status = switch (ex.category()) {
case NOT_FOUND -> HttpStatus.NOT_FOUND; // 404
case CONFLICT -> HttpStatus.CONFLICT; // 409
case VALIDATION -> HttpStatus.BAD_REQUEST; // 400 (or 422, decided once for all services)
case UNAVAILABLE -> HttpStatus.SERVICE_UNAVAILABLE; // 503
case INTERNAL -> HttpStatus.INTERNAL_SERVER_ERROR; // 500
};
ProblemDetail pd = ProblemDetail.forStatusAndDetail(status, ex.getMessage());
pd.setType(URI.create("https://errors.example.com/" + ex.code()));
pd.setProperty("code", ex.code());
pd.setProperty("retryable", ex.retryable());
pd.setProperty("correlationId", MDC.get("correlationId"));
var builder = ResponseEntity.status(status);
if (ex.retryable()) builder.header(HttpHeaders.RETRY_AFTER, "5");
return builder.body(pd);
}
}
Categories, status codes and handling
CategoryHTTP statusRetryableCaller should
NOT_FOUND404noshow not found, stop
CONFLICT409no (maybe after re-reading)reload state, ask the user
VALIDATION400 or 422nofix the input
UNAVAILABLE503 with Retry-Afteryesretry with backoff
INTERNAL500no by defaultreport with correlation ID
One table, owned by the platform team, used by every service.

Because the switch is an expression over an enum with no default branch, adding a new category without a mapping fails to compile, which keeps the mapping complete. Exceptions that are not PlatformException, such as a NullPointerException from a bug, fall to a separate handler that returns a generic 500 problem with only the correlation ID and logs the full trace on the server.

4Making Retryability Explicit

Resilience libraries such as Resilience4j or Spring Retry need to know which failures are worth retrying. If they guess from the exception type, they guess wrong: retrying a validation error wastes time, and not retrying a brief outage fails requests that would have succeeded. So the library states it directly with retryable(), and the shared resilience configuration retries only exceptions where it returns true.

The flag is decided per category by default, but a subclass can override it. For example, a ConflictException caused by an optimistic locking failure can be retryable if the operation re-reads the data first, while a duplicate-key conflict is not. Making this explicit in code, rather than buried in a retry configuration, means the person who throws the exception decides, because they know the most about it.

5Keeping It Safe and Stable Over Years

Messages travel far: into logs, into problem responses, into tickets and screenshots. So the rule is that no secrets and no personal data go into messages or context fields: no passwords, tokens, card numbers, email addresses or full request bodies. If an identifier is sensitive, we log a reference to it instead. The handler also never returns stack traces or exception class names to clients.

The exception types and error codes are a public API of the library. Removing a subclass, changing a code's meaning or moving a type to a different category is a breaking change and follows the library's versioning rules: deprecate first, keep both for a release cycle, then remove in a major version. New codes can be added freely. We also publish the code registry as a page clients can read, with the meaning of each code and whether it is retryable.

6Follow-up questions

Should the hierarchy use checked exceptions?

No. A shared library used across many services should not force every caller to declare or catch its exceptions, and Spring's own exceptions are unchecked for the same reason. Expected business outcomes that callers must handle, such as an insufficient balance, are better represented as return types, while exceptions cover failures.

How do we handle errors from downstream services that use the same library?

The client library can read the problem response, recognise the code and category, and rethrow the matching PlatformException with the original code and the HTTP response as context. That way an Unavailable from service C becomes an Unavailable in service B, retry decisions stay consistent, and the correlation ID links the logs across services.

Where do metrics fit in?

The shared handler can increment a counter tagged with category and code for every error it maps. Dashboards then show, per service, how many 404s, conflicts and dependency failures happen, and an alert can fire on a rise in UNAVAILABLE or INTERNAL rather than on all errors, which would be noisy.

7Conclusion

In this answer, we designed a small exception hierarchy organized by how callers handle errors rather than by where they came from. A base PlatformException carries a stable error code, structured context, a category and an explicit retryable flag, and always accepts a cause. One shared @RestControllerAdvice maps categories to HTTP statuses and RFC 9457 problem details, messages never carry secrets or personal data, and codes and types are treated as a versioned public API.

What to say in the interviewAbout 80 seconds aloud

Open with

I would keep the hierarchy small and organized by how the caller should react, not by source. So a base PlatformException, unchecked, with subclasses like NotFound, Conflict, Validation and Unavailable, maybe one or two more.

Then, if they want more

The base carries a stable machine-readable error code, like ORDER_NOT_FOUND, structured context fields with safe values, a category, and an explicit retryable flag, and every constructor accepts a cause so translation never loses the original. Messages are for humans and can change; clients and dashboards match on the code.

Then I map categories to HTTP once, in a shared @RestControllerAdvice shipped in a starter, producing RFC 9457 problem details with Spring's ProblemDetail: 404, 409, 400, 503 with Retry-After, and 500 for unexpected errors, with the code, the retryable flag and a correlation ID in the body, and never a stack trace.

Resilience libraries use the retryable flag, so validation errors are never retried and dependency outages are. I never allow secrets or personal data in messages or context because they reach logs and clients.

And I treat the codes and types as a versioned public API: new codes are additive, changes go through deprecation, and there is a published registry of codes.

About this answer

Last updated
12 November 2026
Versions it names
Spring Framework 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Design an exception hierarchy for a shared platform library used by many services...": https://scrivio-interview-library.netlify.app/java/exceptions/27dc9f8516/