0Pricing
Spring Boot 4 Microservices & REST APIs · Урок

Детали проблемы (RFC 7807)

Возвращайте стандартизированные ответы об ошибках

«Детали проблемы (RFC 7807)» — бесплатный урок Spring Boot 4 Microservices & REST APIs на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Microservices & REST APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

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

Часто задаваемые вопросы

Урок «Детали проблемы (RFC 7807)» бесплатный?

Да — полный текст урока «Детали проблемы (RFC 7807)» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Microservices & REST APIs, подпишись на CoddyKit PRO. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Чему я научусь в уроке «Детали проблемы (RFC 7807)»?

Возвращайте стандартизированные ответы об ошибках Ты практикуешь Spring Boot 4 Microservices & REST APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Boot 4 Microservices & REST APIs?

Предыдущий опыт не требуется. Spring Boot 4 Microservices & REST APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Детали проблемы (RFC 7807)»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Boot 4 Microservices & REST APIs?

Да. Каждый урок Spring Boot 4 Microservices & REST APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Проверка бинов с помощью @Valid
  2. Пользовательские валидаторы
  3. @ControllerAdvice и @ExceptionHandler
  4. Детали проблемы (RFC 7807)
← Назад к Spring Boot 4 Microservices & REST APIs