– Guard4j events describe what happens in your domain, not how you measure it.
Production-grade error handling and observability for Java applications. A small framework-agnostic core (guard4j-api) plus a Spring Boot starter; Quarkus and Micronaut adapters are planned.
Enterprise Java applications typically suffer from inconsistent error handling that breaks down in production:
- Generic
Map<String, Object>error responses that clients can't reliably parse - Framework-specific error handling that doesn't work when you switch frameworks
- No built-in observability - errors disappear into logs without metrics or alerting
- Testing nightmares where MockMvc tests pass but production servlet errors fail
Errors are type-safe enums that implement only the classification dimensions they need (WebError for the HTTP status, Categorizable for retry logic, Severable for log level and alerting). Context goes into the exception fluently:
throw new Guard4jException(CoreError.BUSINESS_RULE_VIOLATION)
.with("rule", "DAILY_TRANSFER_LIMIT")
.with("limit", 10000)
.with("attempted", 15000);Business events are plain records, emitted through a class-specific emitter. One call produces a Micrometer metric and a structured log entry:
public class PaymentService {
private static final Emitter events = Guard4j.getEmitter(PaymentService.class);
public void processPayment(Payment payment) {
events.info(new PaymentProcessedEvent(payment.id(), payment.amount()));
}
}
public record PaymentProcessedEvent(String paymentId, BigDecimal amount) implements ObservableEvent {}The Spring Boot starter turns every exception into the same response body, whether it is thrown in a controller or reaches the servlet /error page:
{
"timestamp": 1794154387276,
"status": 404,
"error": {
"name": "DATA_NOT_FOUND",
"code": "data-not-found",
"message": "Requested resource not found",
"category": "BUSINESS",
"httpStatus": 404,
"retryable": false,
"severity": "INFO"
},
"data": { "resource": "test-item", "id": "123" },
"fields": null
}error is the error enum with all its dimensions, including dimensions your application adds through its own interfaces. fields lists the invalid fields for validation errors (HTTP 422). The request path is used for logging and metrics only and is not sent to the client.
<dependency>
<groupId>dev.guard4j</groupId>
<artifactId>guard4j-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>Not yet published to Maven Central; build it locally with mvn install (see Build).
Boot's own BasicErrorController backs off automatically; no exclude is needed.
public enum PaymentError implements WebError, Categorizable, Severable {
PAYMENT_GATEWAY_UNAVAILABLE(HttpStatus.SERVICE_UNAVAILABLE, "Payment gateway temporarily unavailable",
Severity.ERROR, Category.EXTERNAL),
DAILY_LIMIT_EXCEEDED(HttpStatus.UNPROCESSABLE_ENTITY, "Daily payment limit exceeded",
Severity.WARN, Category.BUSINESS);
private final HttpStatus httpStatus;
private final String message;
private final Severity severity;
private final Category category;
PaymentError(HttpStatus httpStatus, String message, Severity severity, Category category) {
this.httpStatus = httpStatus;
this.message = message;
this.severity = severity;
this.category = category;
}
@Override public HttpStatus httpStatus() { return httpStatus; }
@Override public String message() { return message; }
@Override public Severity severity() { return severity; }
@Override public Category category() { return category; }
}code() is derived from the name (DAILY_LIMIT_EXCEEDED → daily-limit-exceeded), isRetryable() from the category. See the error definition guide.
@RestControllerAdviceand/errorcontroller sharing one code path (Guard4jErrorHandling)- Mapping of common Spring, validation and persistence exceptions and of all Spring Security exceptions (
SpringError, e.g.BAD_CREDENTIALS,ACCESS_DENIED,INVALID_TOKEN,CSRF_ERROR) - Replaceable beans:
ErrorResolver,ErrorSerializer,ErrorLogger,ErrorMetrics,ErrorEventPublisher(all@ConditionalOnMissingBean) - Micrometer metrics
<prefix>.events(tagsevent_type,level) and<prefix>.http.errors(handled HTTP errors, tagserror,status,category,level); the prefix isguard4j.observability.metrics-prefix, elsespring.application.name, elseguard4j(details) - Structured logs with MDC (
guard4j.event.*,guard4j.context.traceId/userId/correlationId) to the emitting class's logger (observability, logging) - Events are logged without Actuator or Micrometer; the meters need a
MeterRegistry(e.g. fromspring-boot-starter-actuator) guard4j.enabled=falseswitches everything off
| Property | Default | Effect |
|---|---|---|
guard4j.enabled |
true |
everything on or off |
guard4j.level-overrides.<ERROR_NAME> |
– | severity for logging, the level tag and the error event, e.g. guard4j.level-overrides.DATA_NOT_FOUND=DEBUG |
guard4j.include-debug-info |
false |
adds exception class and message to data.debug (development only) |
guard4j.include-stack-trace |
false |
adds the stack trace to data.debug (development only) |
guard4j.web.handler-order |
-100 |
order of Guard4j's @RestControllerAdvice; use a higher value to let your own advices go first |
guard4j.web.handle-spring-exceptions |
true |
false: Guard4j's advice handles only Guard4jException and validation errors; everything else goes to your handlers and Spring's resolvers first, and what ends on /error is still rendered by Guard4j |
guard4j.observability.metrics-prefix |
spring.application.name, else guard4j |
prefix of all meters |
| Framework | Status | Artifact |
|---|---|---|
| Spring Boot 4.x | ✅ Available | guard4j-spring-boot-starter |
| Quarkus | 💡 Planned | – |
| Micronaut | 💡 Planned | – |
- Java 21+
- Spring Boot 4.0+ (the starter uses Spring Boot 4 APIs, e.g.
org.springframework.boot.web.error.ErrorPage)
mvn clean verify # compiles, runs unit tests (Surefire) and *IT (Failsafe)
mvn clean install # additionally installs the artifacts into ~/.m2Verified with JDK 21 and JDK 25, Maven 3.9.
| Module | Package | Contents |
|---|---|---|
guard4j-api |
dev.guard4j |
Guard4jError, CoreError, Guard4j, ObservableEvent; error/ (dimensions, Guard4jException, HttpStatus), emitter/, observability/ (SPI) |
guard4j-spring |
dev.guard4j.spring |
Spring Boot starter |
Breaking change since 2025-09: the Java package and the Maven groupId moved from
de.ferderer.guard4jtodev.guard4j,AppException/ErrorCodeswere replaced byGuard4jException/CoreError,LevelbySeverity. The Spring Security errors are grouped (AUTH_ACCESS_DENIED→ACCESS_DENIED,AUTH_INVALID_CREDENTIALS→BAD_CREDENTIALS, …, ADR-0069), the handled-error counter is<prefix>.http.errorsinstead of<spring.application.name>.errors, anderrorin the response is an object ($.error.nameinstead of$.error, ADR-0067). The application no longer excludesErrorMvcAutoConfiguration.@Validatedparameter violations answerVALIDATION_CONSTRAINT_VIOLATION(422) instead ofVALIDATION_INVALID_INPUT, andErrorSerializer.serializeValidationtakes the error as first argument. GenericIllegalArgumentException,IllegalStateException,UnsupportedOperationExceptionandSecurityExceptionanswer 500 instead of 400/409/501/403. The empty timer<prefix>.errorsis gone; count warnings and errors with<prefix>.events{level=~"warn|error|fatal"}. Thecategorytag of<prefix>.http.errorsisNONEfor errors without a category. NewCategory.INTERNAL(not retryable, ADR-0076): unexpected exceptions, configuration errors andNOT_IMPLEMENTEDmoved there fromSYSTEMand answer"retryable": false. See docs/adr/.
- Architecture decisions (MADR, each with a validation against the code)
- Error definition guide (German)
Apache License 2.0 - see LICENSE for details (ADR-0075).
Why Guard4j? As an independent consultant since 2001 (Java/Spring since 2009), I've seen the same error handling mistakes in enterprise projects across many companies. Guard4j provides the production-grade error handling and observability that Java applications actually need.
Maintained by Vadim Ferderer.