Designing clear and consistent error responses in a REST API is often harder than it looks. Without a shared standard, each application ends up inventing its own ad-hoc format, which quickly leads to inconsistency and confusion. RFC 7807 - Problem Details for HTTP APIs solves this by defining a simple, extensible JSON structure for error messages.
Problem4J brings this specification into the Spring ecosystem, offering a practical way to model, throw, and handle
API errors using Problem objects. It helps you enforce a consistent error contract across your services, while staying
flexible enough for custom exceptions and business-specific details.
Note that RFC 7807 was later extended in RFC 9457, however core concepts remain the same.
Spring already supports RFC 7807 with ProblemDetail, ErrorResponse and
ResponseEntityExceptionHandler. It works well for framework exceptions and for exceptions written as ErrorResponse,
but leaves a few gaps that Problem4J fills:
- Domain exceptions without boilerplate. In Spring, each custom exception has to extend
ErrorResponseException(or implementErrorResponse), or needs its own@ExceptionHandler. Problem4J maps exceptions declaratively with@ProblemMapping- withtype,title,detailand extensions interpolated from exception fields and request context (e.g.{context.traceId}) - or imperatively withProblemException. - Actionable details for framework errors. Spring's built-in responses use generic details (e.g.
Invalid request content.) and do not tell which field or parameter was wrong. Problem4J adds structured extensions, such aserrorswith field violations, orparam,headerandpropertynaming the invalid input - without exposing raw exception messages. - One place for cross-cutting rules. Application properties can override
type,titleandinstancewith templates, and inject a trace ID from a request header into every response. - Immutable, framework-independent model.
Problemis immutable (unlikeProblemDetail) and comes fromproblem4j-core, so the same model and JSON mapping (Jackson, Gson) can be used outside Spring, e.g. in API clients. - Same behavior in WebMVC and WebFlux, auto-configured for Spring Boot. Every component can be replaced
(
@ConditionalOnMissingBean) or disabled via properties, and existingErrorResponseexceptions keep working.
Extensive usage manual explaining library features can be found on GitHub Pages.
The primary ways to produce a Problem response are:
- Implementing a custom
ProblemResolver(or registering one via the Kotlin DSL). - Annotating an exception class with
@ProblemMapping. - Throwing a
ProblemExceptionwith a manually builtProblem.
For more details about each method, please visit https://problem4j.github.io/.
Keeps domain exceptions free of annotations and fixed superclasses, and works also for exceptions you can't modify (e.g. from third-party libraries).
@Component
public class ExampleExceptionResolver implements ProblemResolver {
@Override
public Class<? extends Exception> getExceptionClass() {
return ExampleException.class;
}
@Override
public Problem resolve(
ProblemContext context, Exception ex, HttpHeaders headers, HttpStatusCode status) {
return Problem.builder()
.type("errors/invalid-request")
.title("Invalid Request")
.status(400)
.detail("bad input for user " + ((ExampleException) ex).getUserId())
.extension("userId", ((ExampleException) ex).getUserId())
.build();
}
}It would produce following response with application/problem+json.
{
"type": "errors/invalid-request",
"title": "Invalid Request",
"status": 400,
"detail": "bad input for user u-456",
"userId": "u-456"
}Since 3.1.0, in Kotlin, the same resolver can also be registered via a simplified DSL.
@Configuration
class ExampleExceptionResolverConfiguration {
@Bean
fun exampleProblemResolver(): ProblemResolver = problemResolver<ExampleException> { ex ->
type("errors/invalid-request")
title("Invalid Request")
status(400)
detail("bad input for user ${ex.userId}")
extension("userId", ex.userId)
}
}It would produce the same response as the resolver above.
Declarative mapping for exceptions you own, without writing a resolver. Fields and request context can be
interpolated into Problem values, and the annotation is inherited by subclasses.
@ProblemMapping(
type = "errors/invalid-request",
title = "Invalid Request",
status = 400,
detail = "{message}: {fieldName}",
extensions = {"userId", "fieldName"})
public class ExampleException extends RuntimeException {
private final String userId;
private final String fieldName;
public ExampleException(String userId, String fieldName) {
super("bad input for user " + userId);
this.userId = userId;
this.fieldName = fieldName;
}
}It would produce following response with application/problem+json.
{
"type": "errors/invalid-request",
"title": "Invalid Request",
"status": 400,
"detail": "bad input for user u-123: age",
"userId": "u-123",
"fieldName": "age"
}Simplest for ad-hoc errors, but ties exceptions to Problem4J superclass and moves response building to the throw site.
throw new ProblemException(Problem.of("Invalid Request", 400, "not a valid json"));It would produce following response with application/problem+json.
{
"title": "Invalid Request",
"status": 400,
"detail": "not a valid json"
}Add library as dependency to Maven or Gradle. See the actual versions on Maven Central. Add it along with repository in your dependency manager. Java 17 or higher is required to use this library.
It's assumed that Spring Boot will be already present in your project dependencies, as problem4j-spring is only an
extension to it and does not bring it transitively.
- Maven:
<dependencies> <!-- pick the one for your project --> <dependency> <groupId>io.github.problem4j</groupId> <artifactId>problem4j-spring-webflux</artifactId> <version>${version}</version> </dependency> <dependency> <groupId>io.github.problem4j</groupId> <artifactId>problem4j-spring-webmvc</artifactId> <version>${version}</version> </dependency> </dependencies>
- Gradle (Kotlin DSL):
dependencies { // pick the one for your project implementation("io.github.problem4j:problem4j-spring-webflux:${version}") implementation("io.github.problem4j:problem4j-spring-webmvc:${version}") }
This project contains three major versions, dedicated to Spring Boot 3 and 4.
problem4j.github.io- Full documentation of all projects from Problem4J family.problem4j-core- Core library definingProblemmodel andProblemException.problem4j-jackson- Jackson module for serializing and deserializingProblemobjects.problem4j-spring- Spring modules extendingResponseEntityExceptionHandlerfor handling exceptions and returningProblemresponses.
Expand...
Note that Java 21+ is recommended for local development.
The produced artifacts are compatible with Java 17 thanks to options.release = 17 in Gradle JavaCompile tasks.
This means that regardless of the Java version used to run Gradle, the resulting bytecode remains compatible.
The default Gradle tasks include spotlessApply (for code formatting) and build (for compilation and tests).The
simplest way to build the project is to run:
./gradlewTo execute tests use test task. Tests do not change options.release so newer Java API can be used.
./gradlew testTo format the code according to the style defined in build.gradle.kts rules use spotlessApply
task. Note that building will fail if code is not properly formatted.
./gradlew spotlessApplyTo publish the built artifacts to local Maven repository, use publishToMavenLocal task.
./gradlew publishToMavenLocalNote that for using Maven Local artifacts in target projects, you need to add mavenLocal() repository.
repositories {
mavenLocal()
mavenCentral()
}