Logo Errors

Errors

Tổ chức
api-platform
errors

Handles errors in API Platform — RFC 7807 Problem Details responses, mapping exceptions to HTTP status (exception_to_status, per-operation exceptionToStatus), #[ErrorResource] domain error resources, the 422 validation violations shape, and safely exposing/hiding exception messages. Use when the user mentions error responses, problem+json, HTTP status codes for exceptions, custom error formats, domain exceptions from a provider/processor, 404/409/422 mapping, validation error output, or leaking internal error messages.

Tổng quan

Nhà phát hànhapi-platform
Kho mãskillset
Tên kỹ năngerrors
Sao
29
Bản fork
1
Tệp đi kèm
Chỉ có hướng dẫn
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Đầy đủ trong hướng dẫn

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được api-platform công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Errors trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/api-platform/skillset/tree/main/skills/errors
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/api-platform/skillset.git /tmp/skillset
mkdir -p .claude/skills
cp -r /tmp/skillset/skills/errors .claude/skills/errors
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Errors trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Errors ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Errors không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Error Handling

API Platform converts every thrown exception into a structured error response. With rfc_7807_compliant_errors (the default since 3.1) errors are emitted as RFC 7807 Problem Details — application/problem+json for JSON clients, the Hydra error shape for JSON-LD. You rarely build error bodies by hand; you control the status code and how much of the message is exposed.

How the status code is chosen

For a thrown exception, API Platform resolves the status in this order (Symfony):

  1. exception_to_status mapping (global or per-resource/operation) — first match wins
  2. Symfony HttpExceptionInterface → its status
  3. ApiPlatform\Metadata\Exception\ProblemExceptionInterface with a status → use it
  4. ApiPlatform\Metadata\Exception\HttpExceptionInterface → its status
  5. Defaults: RequestExceptionInterface → 400, ValidationException → 422
  6. The status declared on an #[ErrorResource]
  7. Fallback → 500

Mapping exceptions to status

Throw a plain domain exception from your business layer, then map it. Global config:

yaml
# config/packages/api_platform.yaml
api_platform:
    exception_to_status:
        # keep the defaults — removing them changes built-in behavior
        Symfony\Component\Serializer\Exception\ExceptionInterface: 400
        ApiPlatform\Validator\Exception\ValidationException: 422
        # your mappings
        App\Exception\ProductNotFoundException: 404
        Doctrine\ORM\OptimisticLockException: 409

Per resource / per operation with exceptionToStatus — operation overrides resource overrides global:

php
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use App\Exception\ProductNotFoundException;
use App\Exception\ProductWasRemovedException;

#[ApiResource(
    exceptionToStatus: [ProductNotFoundException::class => 404],
    operations: [
        new Get(exceptionToStatus: [ProductWasRemovedException::class => 410]),
    ],
)]
class Product {}

A plain exception mapped this way is flattened — API Platform turns it into an HttpException and loses any custom properties. To keep structured fields, use an #[ErrorResource] (below) instead of a bare exception + mapping.

Domain exceptions thrown from providers/processors

The natural place to raise these is inside a state provider or processor (see state-provider / state-processor) — e.g. a processor that rejects a write because a business invariant fails:

php
use ApiPlatform\State\ProcessorInterface;
use ApiPlatform\Metadata\Operation;
use App\Exception\InsufficientStockException;

final class OrderProcessor implements ProcessorInterface
{
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
    {
        if ($data->quantity > $this->stock->available($data->sku)) {
            throw new InsufficientStockException();  // mapped to 409 via exceptionToStatus
        }
        // ... persist
    }
}

Message scope: don't leak internals

The message handling is status-dependent and is a real security control:

  • status >= 500: the message is shown only in dev/test. In production a generic message replaces it — so a RuntimeException("DB host db-prod-3 refused") never reaches clients.
  • status < 500: your message is sent to the client.

So a domain 404/409/422 message is client-visible by design — write those messages for end users, and never put internal detail in a sub-500 exception.

#[ErrorResource]: structured domain errors

For full control over the body (extra fields, a stable type URI), make the exception an Error resource. It must implement ApiPlatform\Metadata\Exception\ProblemExceptionInterface and carry #[ErrorResource]:

php
use ApiPlatform\Metadata\ErrorResource;
use ApiPlatform\Metadata\Exception\ProblemExceptionInterface;

#[ErrorResource]
class InsufficientStockException extends \Exception implements ProblemExceptionInterface
{
    public function getType(): string    { return '/errors/insufficient-stock'; }
    public function getTitle(): ?string  { return 'Insufficient stock'; }
    public function getStatus(): ?int    { return 409; }
    public function getDetail(): ?string { return $this->getMessage(); }
    public function getInstance(): ?string { return null; }

    public int $availableQuantity = 0;   // extra field, serialized into the body
}

By default the normalization context strips trace, file, line, code, message, traceAsString so a stack trace can't leak through an Error resource. Override that context only if you deliberately want one of those fields.

Documenting domain errors in OpenAPI

Link an Error resource to an operation with errors: so it appears as a documented response in the OpenAPI/Swagger UI (the errors param is typed class-string<ProblemExceptionInterface>[]):

php
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\GetCollection;
use App\Exception\InsufficientStockException;

#[ApiResource(operations: [
    new GetCollection(errors: [InsufficientStockException::class]),
])]
class Order {}

See api-docs for broader OpenAPI customization.

Validation errors (422)

A failed Symfony validation throws ApiPlatform\Validator\Exception\ValidationException, mapped to 422 with a violations array — each entry pairs the offending propertyPath with a human message:

json
{
    "@context": "/contexts/ConstraintViolationList",
    "@type": "ConstraintViolationList",
    "status": 422,
    "violations": [
        { "propertyPath": "email", "message": "This value is not a valid email address." }
    ]
}

To report every malformed field in one 422 instead of failing on the first type mismatch, enable collect_denormalization_errors (see operations). Validation constraints and groups themselves are covered by custom-validator and operations.

Customizing the generic error provider

To reshape all non-validation errors, decorate api_platform.state.error_provider and build the body from ApiPlatform\State\ApiResource\Error:

php
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ApiResource\Error;
use ApiPlatform\State\ProviderInterface;
use Symfony\Component\DependencyInjection\Attribute\AsAlias;

#[AsAlias('api_platform.state.error_provider')]
final class ErrorProvider implements ProviderInterface
{
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): object
    {
        $exception = $context['request']->attributes->get('exception');
        $status = $operation instanceof HttpOperation ? ($operation->getStatus() ?? 500) : 500;

        $error = Error::createFromException($exception, $status);
        if ($status >= 500) {
            $error->setDetail('Something went wrong');   // belt-and-suspenders against leaks
        }

        return $error;
    }
}

Laravel

The RFC 7807 output, the 422 violations shape, #[ErrorResource] + ProblemExceptionInterface, and per-resource/operation exceptionToStatus are all framework-neutral. The differences are configuration and the global error provider:

  • The global exception_to_status map lives in config/api-platform.php (PHP array), not YAML. It ships with Illuminate\Auth\AuthenticationException => 401 and Illuminate\Auth\Access\AuthorizationException => 403 — keep these when adding your own.
  • 'error_handler' => ['extend_laravel_handler' => true] lets API Platform format errors raised through Laravel's own handler.
  • To reshape all non-validation errors, bind your own provider for the error operation in a service provider instead of the Symfony #[AsAlias('api_platform.state.error_provider')] decoration shown above; the ApiPlatform\State\ApiResource\Error body is the same.

Checklist

  • Domain exceptions mapped via exceptionToStatus (operation > resource > global)
  • Default exception_to_status entries kept when adding custom ones
  • Structured errors use #[ErrorResource] + ProblemExceptionInterface, not flattened exceptions
  • No internal detail in sub-500 exception messages (those reach clients)
  • Domain errors documented on operations via errors:
  • Validation relies on the built-in 422 violations shape, not a custom one

Câu hỏi thường gặp

Kỹ năng AI Errors làm được gì?

Handles errors in API Platform — RFC 7807 Problem Details responses, mapping exceptions to HTTP status (exception_to_status, per-operation exceptionToStatus), #[ErrorResource] domain error resources, the 422 validation violations shape, and safely exposing/hiding exception messages. Use when the user mentions error responses, problem+json, HTTP status codes for exceptions, custom error formats, domain exceptions from a provider/processor, 404/409/422 mapping, validation error output, or leaking internal error messages.

Vì sao nên dùng Errors trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Errors là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Errors trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/api-platform/skillset/tree/main/skills/errors. TypingMind đọc tệp SKILL.md và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Errors?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Errors với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Errors với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Errors có miễn phí không?

Kỹ năng này được api-platform phát hành trên GitHub. Hãy xem điều khoản giấy phép trong kho mã. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇