Skip to content

Commit

Permalink
fix: 🐛 check error code to prevent data loss
Browse files Browse the repository at this point in the history
  • Loading branch information
64b2b6d12bfe4baae7dad3d01 authored and juanpicado committed Aug 26, 2017
1 parent a91a0d3 commit 93aae05
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions src/lib/storage/local/local-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const fs = require('fs');
const Path = require('path');
const logger = require('../../logger');

/**
* Handle local database.
Expand All @@ -15,10 +16,28 @@ const Path = require('path');
*/
constructor(path) {
this.path = path;
let dbFile;

try {
this.data = JSON.parse(fs.readFileSync(this.path, 'utf8'));
} catch(_) {
this.data = {list: []};
dbFile = fs.readFileSync(this.path, 'utf8');
} catch (err) {
if (err.code === 'ENOENT') { // Only recreate if file not found to prevent data loss
this.data = {list: []};
} else {
logger.logger.error(
'Failed to read package database file, please check the error printed below and fix it manually:\n',
`File Path: ${this.path}\n\n`,
err
);
throw new Error('Package database file unreachable');
}
}

try {
this.data = JSON.parse(dbFile);
} catch(err) {
logger.logger.error(err);
throw new Error(`Package database file corrupted (invalid JSON), please fix it manually.\nFile Path: ${this.path}`);
}
}

Expand Down

0 comments on commit 93aae05

Please sign in to comment.