Skill errors
Gerencia o tratamento de erros e as respostas RFC 7807 Problem Details, mapeando exceções para códigos de status HTTP e criando recursos de erro estruturados.
- Estrelas no GitHub
- 29
- Arquivos
- 1
- Último commit
- 22 de out. de 2026
- Licença
- —
- Ferramentas permitidas
- —
O que a skill errors faz?
errors é uma Agent Skill. Gerencia o tratamento de erros e as respostas RFC 7807 Problem Details, mapeando exceções para códigos de status HTTP e criando recursos de erro estruturados.
Resumo gerado a partir do SKILL.md da skill.
Sobre a skill errors
Gerenciar respostas de erro de API e RFC 7807 Problem Details é o que desenvolvedores que utilizam API Platform fazem com este SKILL. Ele permite o mapeamento sistemático de exceções de domínio para códigos de status HTTP específicos, como 404, 409 ou 422. Um agente deve carregar este SKILL quando um usuário precisar configurar o mapeamento de exceções, lidar com violações de validação ou evitar que detalhes internos do sistema vazem nas respostas do cliente.
O SKILL fornece ferramentas para criar recursos de erro estruturados usando o atributo ErrorResource e ProblemExceptionInterface. Isso garante que erros complexos incluam campos personalizados e URIs estáveis, em vez de serem simplificados em mensagens genéricas. Ele também oferece suporte para documentar esses erros no OpenAPI/Swagger UI, vinculando-os a operações específicas. Esteja você trabalhando com Symfony ou Laravel, o SKILL ajuda a manter saídas application/problem+json consistentes e gerencia a visibilidade das mensagens de erro com base no código de status HTTP.
O que um agente pode fazer com ela
- 1Mapear exceções de domínio para códigos de statusConfigurar o sistema para retornar um status 404 quando uma exceção de produto específica for lançada.
- 2Criar recursos de erro de domínio estruturadosDefinir uma classe de erro personalizada que inclua campos serializados extras, como a quantidade disponível.
- 3Prevenir o vazamento de mensagens internasGarantir que mensagens de erro sensíveis do banco de dados sejam substituídas por texto genérico em ambientes de produção.
- 4Documentar erros em especificações de APIAdicionar tipos de erro específicos a uma operação para que eles apareçam na documentação do Swagger UI.
Escrito a partir do SKILL.md da skill. Cada caso de uso é verificado com uma citação dele.
Como instalar a skill errors
Cada comando copia a pasta da skill para o diretório de skills do cliente. Reinicie o cliente ou inicie uma nova sessão para carregá-la.Instalar a skill errors no Plugin
/plugin marketplace add api-platform/skillset /plugin install api-platform@api-platform-skillset
Instalar a skill errors no Claude Code
~/.claude/skills/errors/SKILL.md
$ npx degit api-platform/skillset/skills/errors ~/.claude/skills/errorsInstalar a skill errors no Claude Code (project)
.claude/skills/errors/SKILL.md
$ npx degit api-platform/skillset/skills/errors .claude/skills/errorsInstalar a skill errors no Codex
~/.agents/skills/errors/SKILL.md
$ npx degit api-platform/skillset/skills/errors ~/.agents/skills/errorsInstalar a skill errors no Gemini CLI
~/.gemini/skills/errors/SKILL.md
$ npx degit api-platform/skillset/skills/errors ~/.gemini/skills/errorsInstalar a skill errors no Claude.ai
npx degit api-platform/skillset/skills/errors errors && zip -r errors.zip errors # claude.ai → Customize → Skills → + → Create skill → Upload a skill → errors.zip
SKILL.md
Ver no GitHubError 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):
exception_to_statusmapping (global or per-resource/operation) — first match wins- Symfony
HttpExceptionInterface→ its status ApiPlatform\Metadata\Exception\ProblemExceptionInterfacewith a status → use itApiPlatform\Metadata\Exception\HttpExceptionInterface→ its status- Defaults:
RequestExceptionInterface→ 400,ValidationException→ 422 - The status declared on an
#[ErrorResource] - Fallback → 500
Mapping exceptions to status
Throw a plain domain exception from your business layer, then map it. Global config:
# 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:
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
HttpExceptionand 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:
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]:
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>[]):
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:
{
"@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:
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_statusmap lives inconfig/api-platform.php(PHP array), not YAML. It ships withIlluminate\Auth\AuthenticationException => 401andIlluminate\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; theApiPlatform\State\ApiResource\Errorbody is the same.
Checklist
- Domain exceptions mapped via
exceptionToStatus(operation > resource > global) - Default
exception_to_statusentries 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
violationsshape, not a custom one
Arquivos desta skill
1Perguntas sobre a skill errors
Como instalo a skill errors no Claude Code?
Execute npx degit api-platform/skillset/skills/errors ~/.claude/skills/errors. O Claude Code carrega skills de ~/.claude/skills (todos os projetos) ou .claude/skills (um projeto) e usa uma skill quando a descrição dela corresponde à tarefa.
Quais clientes podem usar a skill errors?
Qualquer cliente que leia o formato Agent Skills: Claude Code, Codex, Gemini CLI e claude.ai (envie como ZIP). Scripts da skill são executados apenas onde o cliente permite execução de código.
Como o API Platform escolhe o código de status HTTP para uma exceção?
Ele resolve o status seguindo uma ordem específica: mapeamento exception_to_status, Symfony HttpExceptionInterface, ProblemExceptionInterface ou padrões como 400 para RequestExceptionInterface.
Qual é a diferença entre mapear uma exceção comum e usar um #[ErrorResource]?
Uma exceção comum mapeada via exception_to_status é convertida em uma HttpException, perdendo propriedades personalizadas. O uso de #[ErrorResource] permite manter campos estruturados e dados extras no corpo da resposta.