# Raccogli errori con ErrorBuilder, registrali con ERROR() e conserva una traccia di audit con AUDIT()

> Rispondi con più errori insieme usando ErrorBuilder, la risposta SUCCESS(), come ERROR() registra i fallimenti e come AUDIT() aggiunge a un file di log chi ha fatto cosa.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: it
Content-SHA256: 5db760777c6ec6540a842d720bee7d2908e507a3173817bf0df8abbe9ac8d535
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

- **`ErrorBuilder`** raccoglie errori. `push(message, [path], [index])` ne aggiunge uno (`path` è il campo a cui appartiene), `push(404)` aggiunge il testo di un codice di stato e imposta lo stato della risposta, `length` li conta, `output()` li restituisce come array di `{ error, path, index }` e `toString()` unisce i messaggi. `$.invalid(builder)` risponde con quell'array e lo stato del builder (400 a meno che sia stato aggiunto un codice di stato).
- **`SUCCESS(value)`** restituisce l'oggetto di un'operazione riuscita: `{ success: true, value: value }`.
- **`ERROR(name)`** restituisce un callback per le API con `function(err)`: quando riceve un errore lo registra con il nome `name`, e non fa nulla se l'errore è vuoto. `ERROR()` è lo stesso callback senza nome. Un errore registrato viene stampato nella console, conteggiato in `F.stats.error`, e gli ultimi dieci sono conservati in `F.errors` come `{ error, name, date }`.
- **`AUDIT($, message, type)`** aggiunge una riga JSON a `logs/audit.log` con chi e dove (`ip`, `ua`, `url` e l'utente quando c'è), il `message`, il `type`, i `params`, `query` e `model` della richiesta in `data`, il nome dell'applicazione in `app` e l'ora in `dtcreated`. `AUDIT('name', $, message, type)` scrive invece in `logs/name.log`.

```js controllers/reports.js
exports.install = function() {
	ROUTE('GET /builder/', builder);
	ROUTE('GET /builder404/', builder404);
	ROUTE('GET /success/', success);
	ROUTE('GET /error/', error);
	ROUTE('GET /audit/', audit);
	ROUTE('GET /audit-read/{name}/', auditread);
};

function builder($) {
	const errors = new ErrorBuilder();
	errors.push('Name is required', 'name');
	errors.push('Age is too low', 'age', 2);
	$.invalid(errors);
}

function builder404($) {
	const errors = new ErrorBuilder();
	errors.push(404);
	$.invalid(errors);
}

function success($) {
	$.json(SUCCESS('saved'));
}

function error($) {
	const before = F.stats.error;
	ERROR('mypart')('Something broke');
	ERROR('mypart')(null);
	ERROR()('Without a name');
	$.json({ counted: F.stats.error - before, last: F.errors.slice(-2).map(n => ({ error: n.error, name: n.name || null, date: n.date instanceof Date || typeof n.date === 'string' })) });
}

function audit($) {
	AUDIT($, 'Opened the report', 'info');
	AUDIT('security', $, 'Checked the access');
	$.json({ ok: true });
}

function auditread($) {
	setTimeout(function() {
		const lines = require('fs').readFileSync(PATH.logs($.params.name + '.log'), 'utf8').trim().split('\n');
		$.json(lines.map(n => JSON.parse(n)));
	}, 300);
}
```
