handle request.js error in node application

223 views Asked by At

I am using request to access data from an api. sometimes, when the api Url is down, node throws error and shuts down with the following error

    at ClientRequest.emit (events.js:315:20)     
    at TLSSocket.socketErrorListener (_http_client.js:426:9)    
    at TLSSocket.emit (events.js:315:20)   
    at emitErrorNT (internal/streams/destroy.js:92:8)    
    at processTicksAndRejections (internal/process/task_queues.js:84:21)         
  errno: 'ENOTFOUND',    
  code: 'ENOTFOUND',    
  syscall: 'getaddrinfo',       
  hostname: APIURL    

is there any way to handle this and prevent node from exiting? my code is

const JSONdata= ()=>{  
 request({url:API_URL2,json:true},(error,response,body)=>{          
        const data=[]       
        var jsondata=body      
        data.push(jsondata)       
        const data2=JSON.stringify(data)        
        fs.writeFile('sample.txt',data2,(err) => { if(error){console.log(error} })})   
2

There are 2 answers

0
James Schnebly On

You can use try/catch blocks that will keep your program running when certain functions error out. Here's a link describing how they work!

https://www.w3schools.com/js/js_errors.asp

0
Athira V Ajit On

Firstly request module has been deprecated request deprecated hence you can try some other packages like axios. Also while trying out api as well as database request try to have a try and catch block and in case of error try to have an appropriate error message displayed to the user.

try{
//your code
res.json("success")
}
catch(err){
   res.json("Looks like something went wrong")
}