refs #5216 fix error handling
gitea/salix/pipeline/head This commit looks good Details

This commit is contained in:
Jorge Penadés 2023-08-24 12:47:10 +02:00
parent bda3937417
commit 386de69bce
3 changed files with 13 additions and 18 deletions

View File

@ -1,3 +1,5 @@
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
Self.remoteMethod('addExpeditionState', {
description: 'Update an expedition state',
@ -31,8 +33,7 @@ module.exports = Self => {
tx = await Self.beginTransaction({});
myOptions.transaction = tx;
}
const promises = [];
let expeditionId;
try {
for (const expedition of expeditions) {
const expeditionStateType = await models.ExpeditionStateType.findOne(
@ -42,30 +43,24 @@ module.exports = Self => {
}
);
if (!expeditionStateType)
throw new Error(`The state code: ${expedition.stateCode} does not exist.`);
throw new UserError(`Invalid state code: ${expedition.stateCode}.`);
const typeFk = expeditionStateType.id;
expeditionId = expedition.expeditionFk;
const existsExpedition = await models.Expedition.findOne({
fields: ['id'],
where: {id: expedition.expeditionFk}
});
if (!existsExpedition)
throw new Error(`The expedition with id: ${expedition.expeditionFk} does not exist.`);
const newExpeditionState = models.ExpeditionState.create({
await models.ExpeditionState.create({
expeditionFk: expedition.expeditionFk,
typeFk,
});
promises.push(newExpeditionState);
}
await Promise.all(promises);
if (tx) await tx.commit();
} catch (e) {
if (tx) await tx.rollback();
if (e instanceof UserError)
throw e;
throw new UserError(`Invalid expedition id: ${expeditionId}.`);
}
};
};

View File

@ -8,7 +8,7 @@ describe('expeditionState addExpeditionState()', () => {
const options = {transaction: tx};
const payload = [
{
expeditionFk: 5,
expeditionFk: 8,
stateCode: 'ON DELIVERY'
},
];
@ -47,7 +47,7 @@ describe('expeditionState addExpeditionState()', () => {
await tx.rollback();
}
expect(error.message).toContain('The state code: DUMMY does not exist.');
expect(error.message).toContain('Invalid state code: DUMMY.');
});
it('should throw an error when expeditionFk does not exist', async() => {
@ -70,6 +70,6 @@ describe('expeditionState addExpeditionState()', () => {
await tx.rollback();
}
expect(error.message).toContain('The expedition with id: 50 does not exist.');
expect(error.message).toContain('Invalid expedition id: 50.');
});
});