Skip to content
ferdererPublic

About

Production-grade error handling and observability for Java. Framework-agnostic core with Spring Boot, Quarkus, and Micronaut integrations. Type-safe error codes, structured responses, automatic metrics and logging.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

72 Commits

Folders and files

Repository files navigation

Guard4j

– 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.

The Problem

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

The Solution

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.

Quick Start (Spring Boot)

1. Add the dependency

<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.

2. Define your errors

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.

3. What the starter provides

  • @RestControllerAdvice and /error controller 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 (tags event_type, level) and <prefix>.http.errors (handled HTTP errors, tags error, status, category, level); the prefix is guard4j.observability.metrics-prefix, else spring.application.name, else guard4j (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. from spring-boot-starter-actuator)
  • guard4j.enabled=false switches everything off

4. Configuration

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 Support

Framework Status Artifact
Spring Boot 4.x ✅ Available guard4j-spring-boot-starter
Quarkus 💡 Planned –
Micronaut 💡 Planned –

Requirements

  • Java 21+
  • Spring Boot 4.0+ (the starter uses Spring Boot 4 APIs, e.g. org.springframework.boot.web.error.ErrorPage)

Build

mvn clean verify     # compiles, runs unit tests (Surefire) and *IT (Failsafe)
mvn clean install    # additionally installs the artifacts into ~/.m2

Verified 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.guard4j to dev.guard4j, AppException/ErrorCodes were replaced by Guard4jException/CoreError, Level by Severity. 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.errors instead of <spring.application.name>.errors, and error in the response is an object ($.error.name instead of $.error, ADR-0067). The application no longer excludes ErrorMvcAutoConfiguration. @Validated parameter violations answer VALIDATION_CONSTRAINT_VIOLATION (422) instead of VALIDATION_INVALID_INPUT, and ErrorSerializer.serializeValidation takes the error as first argument. Generic IllegalArgumentException, IllegalStateException, UnsupportedOperationException and SecurityException answer 500 instead of 400/409/501/403. The empty timer <prefix>.errors is gone; count warnings and errors with <prefix>.events{level=~"warn|error|fatal"}. The category tag of <prefix>.http.errors is NONE for errors without a category. New Category.INTERNAL (not retryable, ADR-0076): unexpected exceptions, configuration errors and NOT_IMPLEMENTED moved there from SYSTEM and answer "retryable": false. See docs/adr/.

Documentation

License

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.

About

Production-grade error handling and observability for Java. Framework-agnostic core with Spring Boot, Quarkus, and Micronaut integrations. Type-safe error codes, structured responses, automatic metrics and logging.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages