Skip to content

Categorize cli errors with fix suggestions (us01/us02)#12414

Open
arthur-wolff wants to merge 7 commits into
inventree:masterfrom
Kelvinmilagres:categorize-CLI-errors-with-fix-suggestions-(US01/US02)
Open

Categorize cli errors with fix suggestions (us01/us02)#12414
arthur-wolff wants to merge 7 commits into
inventree:masterfrom
Kelvinmilagres:categorize-CLI-errors-with-fix-suggestions-(US01/US02)

Conversation

@arthur-wolff

@arthur-wolff arthur-wolff commented Jul 17, 2026

Copy link
Copy Markdown

feat(cli): categorize CLI errors with fix suggestions (US01/US02)

Problem solved

Today, when an InvenTree invoke command fails (e.g., invoke migrate, invoke server), the only generic handling point (task_exception_handler in tasks.py) only handles ModuleNotFoundError manually and prints the raw Python traceback for everything else. This forces whoever is providing support (or a beginner dev setting up the environment) to read a stack trace to understand what actually broke — database down, port in use, file permission, missing dependency, etc. This PR introduces a small, isolated module (cli_error_handling.py) that categorizes the exception and prints standardized output:

[ERROR: <CATEGORY>] <message>
SUGGESTION: <corrective action> (when known)

Relation to the JTBD

JTBD identified in Phase I: "When an error occurs in the CLI, the support analyst/developer wants to understand the root cause immediately, so they don't have to depend on a senior dev or waste time reading tracebacks." This PR directly addresses this job, without touching the application's business logic.

User stories addressed

  • US01 — Semantic categorization and structuring of errors (implemented in this PR)
  • US02 — Corrective action suggestion (implemented in this PR, since the SuggestionProvider is built alongside the categorizer from the start — see justification in documentacao/priorizacao_mvp)
  • US03, US04, US05 — not implemented in this PR; left for future increments (documented in the backlog).

What changes

File Type Description
cli_error_handling.py new ErrorCategory, ExceptionCategorizer, SuggestionProvider, StructuredError, build_structured_error, format_structured_error
test_cli_error_handling.py new 5 tests covering the scenarios from documentacao/cenarios_de_teste
tasks.py edited task_exception_handler now delegates to the new module (see INTEGRACAO_tasks_py.md)

Evidence

Automated tests (5/5 passing):

test_cli_error_handling.py::test_us01_valid_data_categorizes_database_error PASSED
test_cli_error_handling.py::test_us01_unmapped_exception_falls_into_unknown_system PASSED
test_cli_error_handling.py::test_us02_category_with_known_solution_displays_suggestion PASSED
test_cli_error_handling.py::test_us02_category_without_solution_omits_suggestion_line PASSED
test_cli_error_handling.py::test_environment_reuses_category_already_handled_by_task_exception_handler PASSED

Simulated terminal output:

$ invoke migrate
[ERROR: DATABASE] Connection failure on port 5432
SUGGESTION: Check that the database service is running and accessible

$ invoke server (missing dependency)
[ERROR: ENVIRONMENT] No module named 'invoke'
SUGGESTION: Run 'invoke install' to reinstall the correct dependencies

$ invoke <command with unmapped failure>
[ERROR: UNKNOWN_SYSTEM] An unexpected internal failure occurred

AI usage

See documentacao/uso_de_ia — prompts and human refinement decisions documented per item 3.8 of the assignment.

Kelvinmilagres and others added 7 commits June 26, 2026 00:08
…S02)`

### Problema resolvido
Hoje, quando um comando `invoke` da InvenTree falha (ex.: `invoke migrate`,
`invoke server`), o único ponto de tratamento genérico
(`task_exception_handler` em `tasks.py`) só trata `ModuleNotFoundError` de
forma manual e imprime o traceback Python cru para todo o resto. Isso obriga
quem está dando suporte (ou um dev iniciante configurando o ambiente) a ler
stack trace para entender o que de fato quebrou — banco fora do ar, porta
ocupada, permissão de arquivo, dependência faltando, etc.

Este PR introduz um módulo pequeno e isolado (`cli_error_handling.py`) que
categoriza a exceção e imprime uma saída padronizada:

```
[ERRO: <CATEGORIA>] <mensagem>
SUGESTAO: <ação corretiva>   (quando conhecida)
```

### Relação com o JTBD
JTBD identificado na Fase I: *"Quando um erro ocorre na CLI, o analista de
suporte/desenvolvedor quer entender a causa raiz imediatamente, para não
depender de um dev sênior nem perder tempo lendo tracebacks."* Este PR ataca
diretamente esse job, sem tocar na lógica de negócio da aplicação.

### Histórias de usuário atendidas
- **US01** — Categorização e estruturação semântica de erros *(implementada
  neste PR)*
- **US02** — Sugestão de ação corretiva *(implementada neste PR, pois o
  `SuggestionProvider` já nasce junto do categorizador — ver justificativa em
  `documentacao/priorizacao_mvp`)*
- US03, US04, US05 — não implementadas neste PR; ficam para incrementos
  futuros (documentado no backlog).

### O que muda
| Arquivo | Tipo | Descrição |
|---|---|---|
| `cli_error_handling.py` | novo | `ErrorCategory`, `ExceptionCategorizer`, `SuggestionProvider`, `StructuredError`, `build_structured_error`, `format_structured_error` |
| `test_cli_error_handling.py` | novo | 5 testes cobrindo os cenários de `documentacao/cenarios_de_teste` |
| `tasks.py` | editado | `task_exception_handler` passa a delegar para o novo módulo (ver `INTEGRACAO_tasks_py.md`) |

### Evidências

**Testes automatizados (5/5 passando):**
```
test_cli_error_handling.py::test_us01_dados_validos_categoriza_erro_de_banco PASSED
test_cli_error_handling.py::test_us01_excecao_nao_mapeada_cai_em_sistema_desconhecido PASSED
test_cli_error_handling.py::test_us02_categoria_com_solucao_conhecida_exibe_sugestao PASSED
test_cli_error_handling.py::test_us02_categoria_sem_solucao_omite_linha_de_sugestao PASSED
test_cli_error_handling.py::test_ambiente_reaproveita_categoria_ja_tratada_pelo_task_exception_handler PASSED
```

**Saída simulada no terminal:**
```
$ invoke migrate
[ERRO: BANCO_DE_DADOS] Falha de conexao na porta 5432
SUGESTAO: Verifique se o servico de banco de dados esta ativo e acessivel

$ invoke server   (dependência ausente)
[ERRO: AMBIENTE] No module named 'invoke'
SUGESTAO: Execute 'invoke install' para reinstalar as dependencias corretas

$ invoke <comando com falha não mapeada>
[ERRO: SISTEMA_DESCONHECIDO] Ocorreu uma falha interna inesperada
```
*(Substituir por prints reais do terminal de vocês antes de submeter — rodem
os comandos de fato no fork local e capturem a tela.)*

### Uso de IA
Ver `documentacao/uso_de_ia` — prompts e decisões humanas de refino documentados
conforme item 3.8 do enunciado.

### Checklist antes de abrir o PR
- [ ] Rodar `pytest test_cli_error_handling.py` localmente no fork
- [ ] Aplicar as duas edições em `tasks.py` (ver `INTEGRACAO_tasks_py.md`)
- [ ] Testar manualmente pelo menos 1 comando `invoke` real falhando
- [ ] Capturar print real do terminal para substituir a evidência simulada
- [ ] Um dos dois revisa o código do outro e deixa comentários no PR (item 3.12)
@netlify

netlify Bot commented Jul 17, 2026

Copy link
Copy Markdown

Deploy Preview for inventree-web-pui-preview canceled.

Name Link
🔨 Latest commit 0313d0a
🔍 Latest deploy log https://app.netlify.com/projects/inventree-web-pui-preview/deploys/6a59fbc100268900094ead91

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants