Spring Boot 4 Complete Guide · Ders

RFC 7807 ProblemDetail Yanıtları

Spring'in ProblemDetail ve ErrorResponse desteğini kullanarak makine tarafından okunabilir hata yüklerini standartlaştırın.

4. ders / 413 adım

RFC 7807 ProblemDetail Yanıtları, CoddyKit'te ücretsiz bir Spring Boot 4 Complete Guide dersidir. Bu, 4 dersinin 4. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Spring Boot 4 Complete Guide öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Spring Boot 4 Complete Guide kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Why Standardize Error Responses?

When an API fails, clients need a predictable, machine-readable error body. Hand-rolled JSON like {"error": "bad"} varies per endpoint and breaks integrations.

RFC 7807 ("Problem Details for HTTP APIs") defines a single, standard shape for error payloads. Spring Boot has first-class support for it through the ProblemDetail class and the ErrorResponse contract.

  • Consistent across every endpoint
  • Self-documenting via a type URI
  • Extensible with custom properties

The RFC 7807 Media Type and Fields

A Problem Detail response uses the media type application/problem+json and contains these standard members:

  • type — a URI identifying the problem category (defaults to about:blank)
  • title — a short, human-readable summary
  • status — the HTTP status code (e.g. 404)
  • detail — a human-readable explanation specific to this occurrence
  • instance — a URI identifying the specific occurrence (often the request path)

You may also add custom extension members like errorCode or timestamp.

A Sample Problem+JSON Body

Here is what a client actually receives. Note the application/problem+json content type and the standard fields, plus an extension member errorCode.

{
  "type": "https://api.shop.com/problems/out-of-stock",
  "title": "Out of Stock",
  "status": 409,
  "detail": "Product 42 has only 3 units left, but 5 were requested.",
  "instance": "/api/orders",
  "errorCode": "INVENTORY_SHORTAGE"
}

Building a ProblemDetail Programmatically

Spring's ProblemDetail is a simple value object. Use the static factory forStatus() or forStatusAndDetail(), then enrich it with setters.

You can attach custom members via setProperty(name, value). This object serializes directly to application/problem+json.

ProblemDetail problem = ProblemDetail.forStatusAndDetail(
        HttpStatus.NOT_FOUND,
        "Product 42 was not found");
problem.setTitle("Product Not Found");
problem.setType(URI.create("https://api.shop.com/problems/not-found"));
problem.setInstance(URI.create("/api/products/42"));
problem.setProperty("errorCode", "PRODUCT_NOT_FOUND");

Returning ProblemDetail from a Controller

A controller method can return a ProblemDetail directly, or wrap it in a ResponseEntity for full control of headers. Spring sets the status from the ProblemDetail and serializes the body as problem+json.

@GetMapping("/products/{id}")
public ResponseEntity<ProblemDetail> getProduct(@PathVariable Long id) {
    return productRepo.findById(id)
        .map(p -> ResponseEntity.ok().<ProblemDetail>build())
        .orElseGet(() -> {
            ProblemDetail pd = ProblemDetail.forStatusAndDetail(
                HttpStatus.NOT_FOUND, "No product with id " + id);
            pd.setTitle("Product Not Found");
            return ResponseEntity.status(404).body(pd);
        });
}

The ErrorResponse Contract

Returning ProblemDetail manually works, but Spring prefers exceptions to carry their own problem detail. The ErrorResponse interface couples an HTTP status, headers, and a ProblemDetail body.

Spring MVC automatically renders any thrown exception that implements ErrorResponse as problem+json. The convenience class ErrorResponseException is a ready-made implementation you can throw directly.

ProblemDetail pd = ProblemDetail.forStatusAndDetail(
        HttpStatus.CONFLICT, "Email already registered");
pd.setTitle("Duplicate Email");
pd.setProperty("errorCode", "DUPLICATE_EMAIL");

throw new ErrorResponseException(HttpStatus.CONFLICT, pd, null);

Custom Exceptions Implementing ErrorResponse

For domain errors, implement ErrorResponse on your own exception. By extending ErrorResponseException, you inherit status, headers, and body handling, and just supply a configured ProblemDetail.

This keeps error definitions next to the domain logic and out of controllers.

public class OutOfStockException extends ErrorResponseException {

    public OutOfStockException(long productId, int available, int requested) {
        super(HttpStatus.CONFLICT, asProblemDetail(productId, available, requested), null);
    }

    private static ProblemDetail asProblemDetail(long id, int avail, int req) {
        ProblemDetail pd = ProblemDetail.forStatusAndDetail(
            HttpStatus.CONFLICT,
            "Product " + id + " has only " + avail + " left, but " + req + " requested.");
        pd.setType(URI.create("https://api.shop.com/problems/out-of-stock"));
        pd.setTitle("Out of Stock");
        pd.setProperty("errorCode", "INVENTORY_SHORTAGE");
        return pd;
    }
}

Centralizing with @ControllerAdvice

The cleanest pattern: throw plain domain exceptions, then convert them to ProblemDetail in one place using @RestControllerAdvice and @ExceptionHandler.

The handler returns a ProblemDetail; Spring applies the status and problem+json content type automatically.

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ProductNotFoundException.class)
    public ProblemDetail handleNotFound(ProductNotFoundException ex) {
        ProblemDetail pd = ProblemDetail.forStatusAndDetail(
            HttpStatus.NOT_FOUND, ex.getMessage());
        pd.setTitle("Product Not Found");
        pd.setType(URI.create("https://api.shop.com/problems/not-found"));
        pd.setProperty("errorCode", "PRODUCT_NOT_FOUND");
        return pd;
    }
}

Extending ResponseEntityExceptionHandler

Spring's built-in exceptions (validation failures, unreadable bodies, missing parameters) are handled by ResponseEntityExceptionHandler. Since Spring Boot 3, these already produce ProblemDetail bodies.

Extend it in your advice to override or enrich the defaults while keeping framework error handling consistent.

@RestControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, HttpHeaders headers,
            HttpStatusCode status, WebRequest request) {

        ProblemDetail pd = ex.getBody();
        pd.setTitle("Validation Failed");
        pd.setProperty("errorCode", "VALIDATION_ERROR");
        return handleExceptionInternal(ex, pd, headers, status, request);
    }
}

Adding Standard Extension Properties

Common extensions include a timestamp and a traceId for log correlation. Add them in one place so every error carries them.

Use setProperty with serializable values; Instant serializes to an ISO-8601 string by default.

ProblemDetail pd = ProblemDetail.forStatusAndDetail(
        HttpStatus.BAD_REQUEST, "Quantity must be positive");
pd.setTitle("Invalid Quantity");
pd.setProperty("timestamp", Instant.now());
pd.setProperty("traceId", MDC.get("traceId"));
pd.setProperty("errorCode", "INVALID_QUANTITY");

Configuring Defaults in application.yml

Spring can include extra context automatically. Enabling these properties makes the framework attach standard details without code changes.

  • spring.mvc.problemdetails.enabled=true turns on problem+json for built-in exceptions (default in Boot 3+)
  • server.error.include-message and include-binding-errors control how much detail is exposed

Keep sensitive details out of production responses by tuning these flags.

spring:
  mvc:
    problemdetails:
      enabled: true
server:
  error:
    include-message: on_param
    include-binding-errors: on_param
    include-stacktrace: never

Quick Check: Choosing the Right Pattern

You have several domain exceptions (not-found, conflict, forbidden) and want every error across all controllers to emit consistent application/problem+json with shared extensions like traceId. What is the recommended Spring approach?

Recap: RFC 7807 in Spring Boot

You learned how to standardize error payloads with RFC 7807:

  • ProblemDetail is the value object for application/problem+json, with type, title, status, detail, instance plus custom properties.
  • ErrorResponse / ErrorResponseException let exceptions carry their own problem detail.
  • @RestControllerAdvice centralizes conversion of domain exceptions into ProblemDetail.
  • ResponseEntityExceptionHandler already renders Spring's built-in exceptions as problem+json, and can be extended.
  • Add extensions like errorCode, timestamp, and traceId, and tune exposure via application.yml.

The result: a single, predictable, machine-readable error contract across your whole API.

Başlamak ücretsiz

Yapay zeka eğitmeniyle Java öğren — ücretsiz

Tarayıcında gerçek kod yaz ve çalıştır, 7/24 yapay zeka eğitmeninden anında yardım al; web'de ya da uygulamada kaldığın yerden devam et.

Kurslar
21
Dersler
84

Sıkça Sorulan Sorular

“RFC 7807 ProblemDetail Yanıtları” dersi ücretsiz mi?

Evet — “RFC 7807 ProblemDetail Yanıtları” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Spring Boot 4 Complete Guide kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Spring Boot 4 Complete Guide kursu toplamda 4 dersten oluşur.

“RFC 7807 ProblemDetail Yanıtları” dersinde ne öğreneceğim?

Spring'in ProblemDetail ve ErrorResponse desteğini kullanarak makine tarafından okunabilir hata yüklerini standartlaştırın. Spring Boot 4 Complete Guide ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Spring Boot 4 Complete Guide öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Spring Boot 4 Complete Guide, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 4. dersidir.

“RFC 7807 ProblemDetail Yanıtları” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Spring Boot 4 Complete Guide dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Spring Boot 4 Complete Guide dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Bean Validation Kısıtlamaları ve Kısıtlama Grupları
  2. Özel Kısıtlama Açıklamaları Oluşturma
  3. @ControllerAdvice ile Genel Hata Yönetimi
  4. RFC 7807 ProblemDetail Yanıtları
← Spring Boot 4 Complete Guide Sayfasına Dön