Skip to content

Commit e8f463e

Browse files
gsousadevgsousadev
andauthored
[Feature] Removendo dependência para logs do laravel (#6)
* fix: Ajustando Documentação * fix: permitindo o uso do método report * fix: Ajustando nome de configs --------- Co-authored-by: gsousadev <[email protected]>
1 parent f7bb6c2 commit e8f463e

File tree

4 files changed

+112
-22
lines changed

4 files changed

+112
-22
lines changed

README.md

Lines changed: 70 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Laravel Problem Detail Exceptions
22

3-
[![Versão](https://img.shields.io/badge/vers%C3%A3o-1.1.0-beta)](https://github.com/seu-usuario/sua-lib/releases)
3+
[![Versão](https://img.shields.io/badge/vers%C3%A3o-1.2.0-beta)](https://github.com/seu-usuario/sua-lib/releases)
44
[![Licença](https://img.shields.io/badge/licen%C3%A7a-MIT-green)](https://opensource.org/licenses/MIT)
55

66
Esse projeto tem por objetivo prover uma biblioteca Laravel que permite implementar de maneira simples e rápida um padrão de exceptions, seguindo os conceitos da [RFC de problem details](https://datatracker.ietf.org/doc/html/rfc7807)
@@ -21,6 +21,42 @@ php artisan vendor:publish --tag=problem-detail-exceptions
2121

2222
Após a publicação do pacote deve ser criado um arquivo de configuração para o projeto no seguinte caminho: `/config/problem-detail-exceptions.php`.
2323

24+
```php
25+
<?php
26+
27+
use Gsousadev\LaravelProblemDetailExceptions\Enums\ExceptionsFieldsEnum;
28+
29+
return [
30+
'app_name' => env('PROBLEM_DETAIL_EXCEPTION_APP_NAME', 'APP'),
31+
'log_throw' => env('PROBLEM_DETAIL_EXCEPTION_GENERATE_LOGS', true),
32+
'available_fields_list' => [
33+
ExceptionsFieldsEnum::TYPE,
34+
ExceptionsFieldsEnum::TITLE,
35+
ExceptionsFieldsEnum::STATUS,
36+
ExceptionsFieldsEnum::DETAIL,
37+
ExceptionsFieldsEnum::INTERNAL_CODE,
38+
ExceptionsFieldsEnum::MESSAGE,
39+
ExceptionsFieldsEnum::USER_MESSAGE,
40+
ExceptionsFieldsEnum::USER_TITLE,
41+
ExceptionsFieldsEnum::LOCATION,
42+
ExceptionsFieldsEnum::TRACE_ID,
43+
ExceptionsFieldsEnum::PREVIOUS_MESSAGE,
44+
ExceptionsFieldsEnum::PREVIOUS_CODE,
45+
ExceptionsFieldsEnum::PREVIOUS_TYPE,
46+
ExceptionsFieldsEnum::PREVIOUS_LOCATION
47+
48+
],
49+
'renderable_fields_list' => [
50+
ExceptionsFieldsEnum::TITLE,
51+
ExceptionsFieldsEnum::STATUS,
52+
ExceptionsFieldsEnum::USER_MESSAGE,
53+
ExceptionsFieldsEnum::USER_TITLE,
54+
],
55+
56+
];
57+
58+
```
59+
2460
## Configurando
2561

2662
Este pacote permite algumas configurações de customização. Para isso deve-se user o arquivo `problem-detail-exceptions.php`
@@ -29,6 +65,12 @@ Para ter dados coerentes dentro do fluxo é importante ter duas variáveis de am
2965
- **PROBLEM_DETAIL_EXCEPTION_APP_NAME** : Indica o nome que pode aparecer nos logs referente ao nome do projeto ou app que o pacote esta sendo usado.
3066
- **PROBLEM_DETAIL_EXCEPTION_GENERATE_LOGS** : Esta variável permite que sejam ligados e desligados os logs que devem ser publicados em casos de erro.
3167

68+
Ex:
69+
```dotenv
70+
PROBLEM_DETAIL_EXCEPTION_APP_NAME=nome_do_aplicativo
71+
PROBLEM_DETAIL_EXCEPTION_GENERATE_LOGS=true
72+
```
73+
3274
Existe também uma configuração que pode ser feita dentro do arquivo de configuração, informando quais campos devem ser considerados para exceptions de APIs
3375

3476
Existir duas configurações possíveis: Campos que devem ser usados em qualquer contexto chamado `fields` e campos que devem ser mostrados em chamadas HTTP como resposta em casos de erro `renderable_fields`.
@@ -56,8 +98,13 @@ enum ExceptionsFieldsEnum: string
5698
case USER_TITLE = 'user_title';
5799
case LOCATION = 'location';
58100
case TRACE_ID = 'trace_id';
101+
case PREVIOUS_MESSAGE = 'previous_message';
102+
case PREVIOUS_TYPE = 'previous_type';
103+
case PREVIOUS_CODE = 'previous_code';
104+
case PREVIOUS_LOCATION = 'previous_location';
59105
}
60106

107+
61108
```
62109

63110

@@ -137,7 +184,27 @@ try {
137184
}
138185
```
139186

140-
## Padronizando Exceptions de maneira Automática
187+
### Log por Exception
188+
189+
Tambem é possível configurar o log em cada exception usando a opção `$logThrow`. Essa opção permite que possamos
190+
configurar cada excessão para gerar logs, ou não, independente da configuração geral. Caso ela seja omitida a
191+
configuração geral de logs será levada em consideração.
192+
193+
Ex:
194+
195+
```php
196+
...
197+
198+
class ExampleException extends ProblemDetailException
199+
{
200+
protected ?bool $logThrow = true
201+
202+
public function __construct(?\Throwable $previous = null)
203+
204+
...
205+
```
206+
207+
### Padronizando Exceptions de maneira Automática
141208

142209
Existe uma classe que pode ser usada em conjunto com o Handler de Exceptions do Laravel para permitir que todas as
143210
exceptions lançadas e que passem pelo handler possam ser transformadas e normalizadas no padrão 'Problem Detail'.
@@ -180,7 +247,7 @@ class Handler extends ExceptionHandler
180247

181248
## Contribuindo
182249

183-
O projeto esta em fase de construção da ideia inicial, mas apontamentos de melhorias são muito importantes para o
250+
O projeto esta em fase de construção e apontamentos de melhorias são muito importantes para o
184251
crescimento. Para sugerir uma melhoria use as Issues do github.
185252

186253
## Licença

src/Enums/ExceptionsFieldsEnum.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,8 @@ enum ExceptionsFieldsEnum: string
1414
case USER_TITLE = 'user_title';
1515
case LOCATION = 'location';
1616
case TRACE_ID = 'trace_id';
17+
case PREVIOUS_MESSAGE = 'previous_message';
18+
case PREVIOUS_TYPE = 'previous_type';
19+
case PREVIOUS_CODE = 'previous_code';
20+
case PREVIOUS_LOCATION = 'previous_location';
1721
}

src/Exceptions/ProblemDetailException.php

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ abstract class ProblemDetailException extends Exception
1515
private string $logAppName;
1616
private array $renderableFields;
1717
private array $fields;
18+
protected ?bool $logThrow = null;
1819

1920
public function __construct(
2021
private string $title,
@@ -25,32 +26,45 @@ public function __construct(
2526
private string $internalCode,
2627
private ?\Throwable $previous = null
2728
) {
28-
$this->message = $this->title . ' - ' . $this->detail;
29-
$this->message = $this->previous ? $this->message . ' - ' . $this->previous->getMessage() : $this->message;
29+
$this->message = $this->title;
3030
$this->code = $this->httpStatus;
3131
$this->instance = get_class($this);
3232
$this->logAppName = strtoupper(config('problem-detail-exceptions.app_name'));
33-
3433
$this->validateConfigFields();
3534
$this->renderableFields = $this->generateRenderableFieldsByConfig();
36-
$this->fields = $this->generateFieldsFieldsByConfig();
35+
$this->fields = $this->generateFieldsByConfig();
3736

3837
parent::__construct($this->message, $this->code, $this->previous);
38+
39+
$isDefaultEnableAndLogThrowNull = (is_null($this->logThrow) &&
40+
config('problem-detail-exceptions.log_throw'));
41+
42+
if ($isDefaultEnableAndLogThrowNull || $this->logThrow) {
43+
Log::error(
44+
'[' . $this->logAppName . '][' . $this->internalCode . ']',
45+
$this->toArray()
46+
);
47+
}
3948
}
4049

4150
public function toArray(): array
4251
{
4352
$allFields = [
44-
ExceptionsFieldsEnum::TYPE->value => $this->instance,
45-
ExceptionsFieldsEnum::TITLE->value => $this->title,
46-
ExceptionsFieldsEnum::STATUS->value => $this->httpStatus ?? $this->code,
47-
ExceptionsFieldsEnum::DETAIL->value => $this->detail,
48-
ExceptionsFieldsEnum::INTERNAL_CODE->value => $this->internalCode,
49-
ExceptionsFieldsEnum::MESSAGE->value => $this->message,
50-
ExceptionsFieldsEnum::USER_MESSAGE->value => $this->userMessage,
51-
ExceptionsFieldsEnum::USER_TITLE->value => $this->userTitle,
52-
ExceptionsFieldsEnum::LOCATION->value => $this->file . ':' . $this->line,
53-
ExceptionsFieldsEnum::TRACE_ID->value => data_get(Log::sharedContext(), 'trace_id'),
53+
ExceptionsFieldsEnum::TYPE->value => $this->instance,
54+
ExceptionsFieldsEnum::TITLE->value => $this->title,
55+
ExceptionsFieldsEnum::STATUS->value => $this->httpStatus ?? $this->code,
56+
ExceptionsFieldsEnum::DETAIL->value => $this->detail,
57+
ExceptionsFieldsEnum::INTERNAL_CODE->value => $this->internalCode,
58+
ExceptionsFieldsEnum::MESSAGE->value => $this->message,
59+
ExceptionsFieldsEnum::USER_MESSAGE->value => $this->userMessage,
60+
ExceptionsFieldsEnum::USER_TITLE->value => $this->userTitle,
61+
ExceptionsFieldsEnum::LOCATION->value => $this->file . ':' . $this->line,
62+
ExceptionsFieldsEnum::TRACE_ID->value => data_get(Log::sharedContext(), 'trace_id'),
63+
ExceptionsFieldsEnum::PREVIOUS_MESSAGE->value => $this->previous->getMessage() ?? null,
64+
ExceptionsFieldsEnum::PREVIOUS_TYPE->value => $this->previous::class ?? null,
65+
ExceptionsFieldsEnum::PREVIOUS_CODE->value => $this->previous->getCode() ?? null,
66+
ExceptionsFieldsEnum::PREVIOUS_LOCATION->value => $this->previous->file . ':' . $this->previous->line ??
67+
null,
5468
];
5569

5670
return array_filter(
@@ -78,7 +92,7 @@ function ($key) {
7892

7993
public function report(): bool
8094
{
81-
if (config('problem-detail-exceptions.enable_log_in_exception')) {
95+
if (config('problem-detail-exceptions.log_throw')) {
8296
Log::error(
8397
'[' . $this->logAppName . '][' . $this->internalCode . ']',
8498
$this->toArray()
@@ -88,6 +102,7 @@ public function report(): bool
88102
return true;
89103
}
90104

105+
91106
public function getTitle(): string
92107
{
93108
return $this->title;
@@ -164,7 +179,7 @@ function ($renderableField) {
164179
);
165180
}
166181

167-
private function generateFieldsFieldsByConfig()
182+
private function generateFieldsByConfig()
168183
{
169184
$fields = config('problem-detail-exceptions.available_fields_list');
170185

@@ -176,4 +191,3 @@ function ($field) {
176191
);
177192
}
178193
}
179-

src/config/problem-detail-exceptions.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
return [
66
'app_name' => env('PROBLEM_DETAIL_EXCEPTION_APP_NAME', 'APP'),
7-
'enable_log_in_exception' => env('PROBLEM_DETAIL_EXCEPTION_GENERATE_LOGS', true),
7+
'log_throw' => env('PROBLEM_DETAIL_EXCEPTION_GENERATE_LOGS', true),
88
'available_fields_list' => [
99
ExceptionsFieldsEnum::TYPE,
1010
ExceptionsFieldsEnum::TITLE,
@@ -15,7 +15,12 @@
1515
ExceptionsFieldsEnum::USER_MESSAGE,
1616
ExceptionsFieldsEnum::USER_TITLE,
1717
ExceptionsFieldsEnum::LOCATION,
18-
ExceptionsFieldsEnum::TRACE_ID
18+
ExceptionsFieldsEnum::TRACE_ID,
19+
ExceptionsFieldsEnum::PREVIOUS_MESSAGE,
20+
ExceptionsFieldsEnum::PREVIOUS_CODE,
21+
ExceptionsFieldsEnum::PREVIOUS_TYPE,
22+
ExceptionsFieldsEnum::PREVIOUS_LOCATION
23+
1924
],
2025
'renderable_fields_list' => [
2126
ExceptionsFieldsEnum::TITLE,

0 commit comments

Comments
 (0)