javascript - How correct catch error when i write to a file? - Stack Overflow

I have a problem with catching error in module fs exactly writeFile.I tried to trycatch for catch erro

I have a problem with catching error in module fs exactly writeFile.

I tried to try/catch for catch error and write to logs, but it's not working. In debbuger error don't go on catch block, and after invoke too many times, nothing happiness.

const fs = require('fs');

const writeData = (body) => {
    try{
        const stringData = JSON.stringify(body);
            fs.writeFile('./data76/data.json', stringData, {flag: 'a+'} ,(err) =>{
                if(!err){
                    console.log('file was writed');
                }else {
                    console.error('Error writing new data');
                    throw new Error(err);
                }
            });

    }catch(error){
        console.error('THIS ERROR!!!!!');
         let dataError = JSON.stringify(error);
         fs.open('./logs/error.log', 'wx', (err, fd) => {
             if(!err){
                 fs.writeFile(fd, dataError, (err) => {
                     if(!err){
                         fs.close(fd, (err) => {
                             if(!err){
                                 console.log('log was written success');

                     }else{
                                 console.error('file log wasn\'t closed');                                
                             }
                         });
                     }else{
                        console.error('log wasn\'t writed'); 
                     }
                 });
             }else {
                 fs.writeFile(fd, dataError, (err) => {
                     if(!err){
                         console.log('log was writed');
                     }else {
                         console.error('log wasn\'t writed');
                     }
                 });
             }
         });
    };

};

const body = {
    "name": {
        "first": "John",
        "jobtitle": "Driver"
    },
    "uuid_pany": "ab667468-d7c5-469e-b402-0bd2d71073fa",
    "license_number": "AB58659",
    "phone": "+19019876512",
    "uuid": "08475753",
    "place_id": "place_not_matter",
    "birthday": "10.12.1967"
};

writeData(body);

In result, I waiting for catch error and write it in a file. My personal logger

I have a problem with catching error in module fs exactly writeFile.

I tried to try/catch for catch error and write to logs, but it's not working. In debbuger error don't go on catch block, and after invoke too many times, nothing happiness.

const fs = require('fs');

const writeData = (body) => {
    try{
        const stringData = JSON.stringify(body);
            fs.writeFile('./data76/data.json', stringData, {flag: 'a+'} ,(err) =>{
                if(!err){
                    console.log('file was writed');
                }else {
                    console.error('Error writing new data');
                    throw new Error(err);
                }
            });

    }catch(error){
        console.error('THIS ERROR!!!!!');
         let dataError = JSON.stringify(error);
         fs.open('./logs/error.log', 'wx', (err, fd) => {
             if(!err){
                 fs.writeFile(fd, dataError, (err) => {
                     if(!err){
                         fs.close(fd, (err) => {
                             if(!err){
                                 console.log('log was written success');

                     }else{
                                 console.error('file log wasn\'t closed');                                
                             }
                         });
                     }else{
                        console.error('log wasn\'t writed'); 
                     }
                 });
             }else {
                 fs.writeFile(fd, dataError, (err) => {
                     if(!err){
                         console.log('log was writed');
                     }else {
                         console.error('log wasn\'t writed');
                     }
                 });
             }
         });
    };

};

const body = {
    "name": {
        "first": "John",
        "jobtitle": "Driver"
    },
    "uuid_pany": "ab667468-d7c5-469e-b402-0bd2d71073fa",
    "license_number": "AB58659",
    "phone": "+19019876512",
    "uuid": "08475753",
    "place_id": "place_not_matter",
    "birthday": "10.12.1967"
};

writeData(body);

In result, I waiting for catch error and write it in a file. My personal logger

Share Improve this question asked Jun 23, 2019 at 18:25 Ilya RogatkinIlya Rogatkin 971 silver badge9 bronze badges 1
  • You can't use try/catch for asynchronously thrown exceptions, like those in your writeFile callback. (You can if you use promises and await). Don't throw an error, just put the error handling code in that else block and drop the try. – Bergi Commented Jun 23, 2019 at 18:33
Add a ment  | 

1 Answer 1

Reset to default 4

try/catch outside of await/promises cannot catch errors throw inside of asynchronous callbacks. So, if you're trying to handle an error inside the callback for an fs.writeFile(), you need to insert the error handling code inside the fs.writeFile() callback or (better yet) use the promise versions of file handling and let errors propagate through promises.

In addition, most errors writing to a file are not transient errors. So, it would be rare that trying to write again will actually be a solution and not just encounter the same issue. More typical errors are disk full, media error, volume not responding, etc... Those are unlikely to suddenly work by just trying again. Also, each particular type of error may need a different strategy to deal with. Is there a particular type of error you've encountered that you want to devise a strategy for?

Also, fs.writeFile() will take the file path directly and then it will handle the fs.open() and fs.close() for you. You don't need to manually open it, write to it and close it.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745659642a4638756.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信