Spring Boot Skills
GitHub
API Design

Problem Details RFC 9457

Use when implementing exception mapping or RFC 9457 error responses in Spring Boot 3. Preserve an existing legacy error contract unless migration is requested.

View SKILL.md

Choose the error contract

Inspect existing advice, security entry points and API tests first. Keep one error policy per API. Success DTOs or success envelopes can coexist with Problem Details errors: RFC 9457 specifies errors, not success representations.

For an API using Problem Details, enable Spring's built-in MVC exception handling:

spring:
  mvc:
    problemdetails:
      enabled: true

For WebFlux use spring.webflux.problemdetails.enabled and reactive exception handling; the servlet templates below are not WebFlux handlers.

Domain errors

Use the compiled DomainException together with ProblemDetailExceptionHandler. The handler maps all subclasses using their declared status and stable error code:

Each public class has its own file. These are API-facing exceptions with HTTP status metadata; for a framework-free domain, keep domain exceptions independent and map them in the web adapter. Do not expose arbitrary persistence or infrastructure exception messages.

The advice extends ResponseEntityExceptionHandler to preserve Spring's handling of framework exceptions. Validation returns 400 with field violations; unexpected failures return a generic 500 while retaining the full exception only in server logs. Keep nullable validation messages safe. Filter-level authentication failures need an AuthenticationEntryPoint; authorization failures need an AccessDeniedHandler. Controller advice does not cover the security filter chain. Method-security (@PreAuthorize) denials are the opposite case: AccessDeniedException is thrown inside the dispatcher, so the advice must map it to 403 or the Exception catch-all returns 500.

Response fields

{
  "type": "https://api.example.com/errors/order_not_found",
  "title": "Not Found",
  "status": 404,
  "detail": "Order not found",
  "instance": "/api/orders/123",
  "errorCode": "ORDER_NOT_FOUND"
}

Use project-owned, stable URIs for custom problem types. An explicit type is optional; when omitted it defaults to about:blank. Its title should then match the HTTP status phrase. The HTTP status and the body status must agree. Use application/problem+json for JSON problems. Use extensions such as errorCode or violations for machine-readable details instead of requiring clients to parse human-readable messages.

Verification

Test actual HTTP responses for domain 404/422, validation 400, unexpected 500, and framework errors such as malformed JSON and unsupported methods. Assert content type, status, stable error codes and absence of stack traces or internal messages. Separately test filter 401/403. The repository verification fixture imports these exact templates for both Boot versions.

Official sources

Gotchas

  • Agent handles a different exception class than the domain throws - test the concrete exceptions.
  • Agent forces Problem Details into an existing legacy API - preserve its contract unless asked to migrate.
  • Agent requires an explicit type for every error - about:blank is the default.
  • Agent treats success envelopes and Problem Details as incompatible - only error policy must be consistent.
  • Agent relies on advice for filter exceptions - configure the security handlers separately.
  • Agent returns internal exception messages in 500 responses - log privately and return generic detail.
FROM THE REPOSITORY

Examples & templates

bad-exception-handler.javaexamples
Source on GitHub
// ❌ BAD — returns Map, exposes internals, wrong status codes

@RestControllerAdvice
public class GlobalExceptionHandler {                      // no framework error handling shown

    @ExceptionHandler(OrderNotFoundException.class)
    public Map<String, Object> handleNotFound(OrderNotFoundException ex) {
        return Map.of(                                     // returns Map, not ProblemDetail
            "error", ex.getMessage(),
            "status", 404
        );                                                 // body says 404 but HTTP status remains 200
    }

    @ExceptionHandler(BusinessRuleViolationException.class)
    public ResponseEntity<Map<String, String>> handleBusinessRule(BusinessRuleViolationException ex) {
        return ResponseEntity.ok(                          // returns 200 with error body!
            Map.of("error", ex.getMessage()));             // should be 422 Unprocessable Entity
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleGeneric(Exception ex) {
        return ResponseEntity.status(500).body(Map.of(
            "error", ex.getMessage(),                      // exposes raw exception message (security risk)
            "stackTrace", Arrays.toString(ex.getStackTrace())  // NEVER expose stack traces
        ));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<String> handleValidation(MethodArgumentNotValidException ex) {
        return ResponseEntity.badRequest()
            .body("Validation failed: " + ex.getMessage());  // raw string, no structure
    }
}
good-exception-handler.javaexamples
Source on GitHub
// ✅ GOOD — extends ResponseEntityExceptionHandler, maps the actual domain exception hierarchy, custom properties

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    private static final String ERROR_BASE_URI = "https://api.example.com/errors/";

    @ExceptionHandler(DomainException.class)
    public ProblemDetail handleDomain(DomainException ex, HttpServletRequest request) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(ex.getHttpStatus(), ex.getMessage());
        problem.setType(URI.create(ERROR_BASE_URI + ex.getErrorCode().toLowerCase(java.util.Locale.ROOT)));
        problem.setTitle(ex.getHttpStatus().getReasonPhrase());
        problem.setInstance(URI.create(request.getRequestURI()));
        problem.setProperty("errorCode", ex.getErrorCode());
        return problem;
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, HttpHeaders headers,
            HttpStatusCode status, WebRequest request) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.BAD_REQUEST, "Request validation failed");
        problem.setType(URI.create(ERROR_BASE_URI + "validation"));
        problem.setTitle("Validation Failed");
        problem.setProperty("timestamp", Instant.now());
        problem.setProperty("violations", ex.getBindingResult().getFieldErrors().stream()
            .map(e -> Map.of("field", e.getField(), "message", e.getDefaultMessage() == null ? "Invalid value" : e.getDefaultMessage()))
            .toList());
        return ResponseEntity.badRequest().body(problem);
    }

    // @PreAuthorize denials are thrown inside the dispatcher, so the filter chain's
    // AccessDeniedHandler never sees them — without this the catch-all returns 500.
    @ExceptionHandler(AccessDeniedException.class)
    public ProblemDetail handleAccessDenied(AccessDeniedException ex, HttpServletRequest request) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.FORBIDDEN, "You do not have permission to perform this action");
        problem.setType(URI.create(ERROR_BASE_URI + "forbidden"));
        problem.setTitle("Forbidden");
        problem.setInstance(URI.create(request.getRequestURI()));
        problem.setProperty("timestamp", Instant.now());
        return problem;
    }

    @ExceptionHandler(Exception.class)
    public ProblemDetail handleGeneric(Exception ex, HttpServletRequest request) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
        problem.setType(URI.create(ERROR_BASE_URI + "internal"));
        problem.setTitle("Internal Server Error");
        problem.setInstance(URI.create(request.getRequestURI()));
        problem.setProperty("timestamp", Instant.now());
        log.error("Unhandled exception at {}", request.getRequestURI(), ex);
        return problem;
    }
}
BusinessRuleViolationException.javatemplates
Source on GitHub
package com.example.order.exception;

import com.example.common.exception.DomainException;
import org.springframework.http.HttpStatus;

public class BusinessRuleViolationException extends DomainException {
    public BusinessRuleViolationException(String message) {
        super("BUSINESS_RULE_VIOLATION", HttpStatus.UNPROCESSABLE_ENTITY, message);
    }
}
DomainException.javatemplates
Source on GitHub
package com.example.common.exception;

import org.springframework.http.HttpStatus;

// API-facing exception; keep framework-free domain models separate when required.
public abstract class DomainException extends RuntimeException {
    private final String errorCode;
    private final HttpStatus httpStatus;

    protected DomainException(String errorCode, HttpStatus httpStatus, String message) {
        super(message);
        this.errorCode = errorCode;
        this.httpStatus = httpStatus;
    }

    public String getErrorCode() { return errorCode; }
    public HttpStatus getHttpStatus() { return httpStatus; }
}
InsufficientInventoryException.javatemplates
Source on GitHub
package com.example.order.exception;

import com.example.common.exception.DomainException;
import org.springframework.http.HttpStatus;
import java.util.UUID;

public class InsufficientInventoryException extends DomainException {
    public InsufficientInventoryException(UUID productId, int requested, int available) {
        super("INSUFFICIENT_INVENTORY", HttpStatus.UNPROCESSABLE_ENTITY, "Insufficient inventory for product %s: requested %d, available %d".formatted(productId, requested, available));
    }
}
OrderNotFoundException.javatemplates
Source on GitHub
package com.example.order.exception;

import com.example.common.exception.DomainException;
import org.springframework.http.HttpStatus;
import java.util.UUID;

public class OrderNotFoundException extends DomainException {
    public OrderNotFoundException(UUID orderId) {
        super("ORDER_NOT_FOUND", HttpStatus.NOT_FOUND, "Order not found: " + orderId);
    }
}
ProblemDetailExceptionHandler.javatemplates
Source on GitHub
package com.example.common.exception;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.net.URI;
import java.time.Instant;
import java.util.Map;
import java.util.Locale;

@RestControllerAdvice
public class ProblemDetailExceptionHandler extends ResponseEntityExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(ProblemDetailExceptionHandler.class);

    private static final String ERROR_BASE_URI = "https://api.example.com/errors/";

    @ExceptionHandler(DomainException.class)
    public ProblemDetail handleDomainException(DomainException ex, HttpServletRequest request) {
        HttpStatus status = ex.getHttpStatus();
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(status, ex.getMessage());
        problem.setType(URI.create(ERROR_BASE_URI + ex.getErrorCode().toLowerCase(Locale.ROOT)));
        problem.setTitle(status.getReasonPhrase());
        problem.setInstance(URI.create(request.getRequestURI()));
        problem.setProperty("errorCode", ex.getErrorCode());
        problem.setProperty("timestamp", Instant.now());
        return problem;
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ProblemDetail handleAccessDenied(AccessDeniedException ex, HttpServletRequest request) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.FORBIDDEN, "You do not have permission to perform this action");
        problem.setType(URI.create(ERROR_BASE_URI + "forbidden"));
        problem.setTitle("Forbidden");
        problem.setInstance(URI.create(request.getRequestURI()));
        problem.setProperty("timestamp", Instant.now());
        return problem;
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, HttpHeaders headers,
            HttpStatusCode status, WebRequest request) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.BAD_REQUEST, "Request validation failed");
        problem.setType(URI.create(ERROR_BASE_URI + "validation"));
        problem.setTitle("Validation Failed");
        problem.setProperty("errorCode", "VALIDATION_FAILED");
        problem.setProperty("timestamp", Instant.now());
        problem.setProperty("violations", ex.getBindingResult().getFieldErrors().stream()
            .map(e -> Map.of("field", e.getField(), "message", e.getDefaultMessage() == null ? "Invalid value" : e.getDefaultMessage()))
            .toList());
        return ResponseEntity.badRequest().body(problem);
    }

    @ExceptionHandler(Exception.class)
    public ProblemDetail handleGeneric(Exception ex, HttpServletRequest request) {
        log.error("Unhandled exception at {}", request.getRequestURI(), ex);
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
        problem.setType(URI.create(ERROR_BASE_URI + "internal"));
        problem.setTitle("Internal Server Error");
        problem.setInstance(URI.create(request.getRequestURI()));
        problem.setProperty("timestamp", Instant.now());
        return problem;
    }
}

Verification scope

Compiled sources
Handler, both trees
Runtime checks
Selected HTTP error contracts

Coverage describes checked-in fixtures, not a guarantee for every snippet or project.

Coverage matrix & agent evidence
ADD TO YOUR AGENT

Install Boot 3 skills

claude plugin marketplace add rrezartprebreza/spring-boot-skills
claude plugin install spring-boot-3-skills@spring-boot-skills