0Pricing
Spring Boot 4 Microservices & REST APIs · Lección

Detalles del problema (RFC 7807)

Devuelva respuestas de error estandarizadas

Detalles del problema (RFC 7807) es una lección gratuita de Spring Boot 4 Microservices & REST APIs en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Spring Boot 4 Microservices & REST APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

A Standard for API Errors

Every team inventing its own error JSON leads to chaos for API consumers. RFC 7807 defines Problem Details — a standard, machine-readable error format with a media type of application/problem+json.

The Problem Details Fields

The standard defines a small set of fields:

  • type — a URI identifying the problem kind
  • title — short, human-readable summary
  • status — the HTTP status code
  • detail — specifics for this occurrence
  • instance — URI of the specific occurrence

Spring’s ProblemDetail

Spring Framework 6 / Boot 3 ship a built-in ProblemDetail class that models RFC 7807 directly. You construct it with a status and customize the standard fields.

ProblemDetail pd = ProblemDetail.forStatusAndDetail(
        HttpStatus.NOT_FOUND, "Order 42 was not found");
pd.setTitle("Order Not Found");
pd.setType(URI.create("https://errors.example.com/order-not-found"));

Returning ProblemDetail

Return a ProblemDetail from a controller or exception handler. Spring serializes it as application/problem+json with the right status.

@ExceptionHandler(OrderNotFoundException.class)
public ProblemDetail handle(OrderNotFoundException ex) {
    ProblemDetail pd = ProblemDetail.forStatusAndDetail(
        HttpStatus.NOT_FOUND, ex.getMessage());
    pd.setTitle("Order Not Found");
    return pd;
}

Enabling Built-in Problem Details

Spring Boot can convert its own framework exceptions into Problem Details automatically when you enable the property, giving consistent errors even for built-in failures.

spring:
  mvc:
    problemdetails:
      enabled: true

Extending with Custom Properties

RFC 7807 permits extension members. Add domain-specific data — an error code, a correlation id, or field errors — via setProperty.

pd.setProperty("errorCode", "ORDER_NOT_FOUND");
pd.setProperty("correlationId", correlationId);
pd.setProperty("timestamp", Instant.now());

ResponseEntityExceptionHandler

Extend ResponseEntityExceptionHandler in your @ControllerAdvice to inherit handlers for Spring’s standard exceptions, then override the hooks to shape them as Problem Details.

@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    // override protected handle... methods to customize
}

Problem Details for Validation

Override the validation hook to express field errors as a Problem Details body with an extension array, giving clients structured, standard validation feedback.

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
        MethodArgumentNotValidException ex, HttpHeaders h,
        HttpStatusCode status, WebRequest req) {
    ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
    pd.setTitle("Validation Failed");
    pd.setProperty("errors", ex.getBindingResult().getFieldErrors().stream()
        .map(e -> Map.of("field", e.getField(), "message", e.getDefaultMessage()))
        .toList());
    return ResponseEntity.badRequest().body(pd);
}

Why the type URI Matters

The type URI gives each problem a stable identity clients can branch on — more robust than parsing human text. Point it at documentation describing the error and how to recover.

Content Negotiation

Problem Details responses carry the application/problem+json content type. Clients can detect this media type to distinguish structured errors from normal success payloads.

HTTP/1.1 404 Not Found
Content-Type: application/problem+json

{ "type": "...", "title": "Order Not Found", "status": 404, "detail": "..." }

Adopting the Standard

Using Problem Details makes your API errors predictable and interoperable:

  • One shape across all endpoints and frameworks
  • Machine-readable type for client logic
  • Extensible for domain-specific detail

Quick Check

Test your understanding of RFC 7807.

Recap

Problem Details standardize API errors.

  • RFC 7807 defines type, title, status, detail, instance
  • Spring’s ProblemDetail models it; served as application/problem+json
  • Enable built-in conversion via spring.mvc.problemdetails.enabled
  • Add extension members with setProperty
  • Extend ResponseEntityExceptionHandler to shape framework errors

Preguntas frecuentes

¿La lección «Detalles del problema (RFC 7807)» es gratis?

Sí — el texto completo de «Detalles del problema (RFC 7807)» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Spring Boot 4 Microservices & REST APIs, actualiza a CoddyKit PRO. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.

¿Qué aprenderé en «Detalles del problema (RFC 7807)»?

Devuelva respuestas de error estandarizadas Practicas Spring Boot 4 Microservices & REST APIs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Spring Boot 4 Microservices & REST APIs?

No se requiere experiencia previa. Spring Boot 4 Microservices & REST APIs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Detalles del problema (RFC 7807)»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Spring Boot 4 Microservices & REST APIs?

Sí. Cada lección de Spring Boot 4 Microservices & REST APIs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Validación de beans con @Valid
  2. Validadores personalizados
  3. @ControllerAdvice y @ExceptionHandler
  4. Detalles del problema (RFC 7807)
← Volver a Spring Boot 4 Microservices & REST APIs