Closed jordidh closed 1 year ago
Primera aproximació, en totes les crides retornar en el body un objecte amb la següent estructura:
{
"status": "OK/ERROR",
"data": ... ,
"errors": [
{
"code": "auth-0001",
"message": "Incorrect username and password",
"detail": "Ensure that the username and password included in the request are correct",
"help": "https://example.com/help/error/auth-0001"
},
...
]
}
Exemple mòdul ApiResult
class ApiResult {
/**
*
* @param {*} status
* @param {*} data
* @param {*} error : object from class ApiError
*/
constructor(status, data, error) {
this.status = status;
//this.message = message;
this.data = data;
this.errors = [];
this.errors.push(error);
}
}
class ApiError {
constructor(code, message, detail, help) {
this.code = code;
this.message = message;
this.detail = detail;
this.help = help;
}
}
module.exports = ApiResult;
Com fer-ho servir:
const ApiResult = require("../../api/ApiResult");
...
function GET(req, res, next) {
try {
if (req.query.id) {
// Retornem un contenidor concret
let container = containerService.getContainer(req.query.id);
if (container === undefined) {
res.status(404).json(new ApiResult(404, null, new ApiError('CONTAINER-001', null, `Container with id ${req.query.id} not found`)));
} else {
res.status(200).json(new ApiResult(200, container, null);
}
} else {
// Retornem tots els contenidors
let containers = containerService.getContainers();
res.status(200).json(new ApiResult(200, containers, null);
}
} catch (ex) {
res.status(500).json(new ApiResult(500, null, new ApiError('CONTAINER-002', null, `Exception ${ex.message}`)));
}
}
Objectiu: Definir una estructura única per tots els errors que retornin les API, per tal de simplificar el tractament d'errors per part dels clients.