0

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} })})      
                   
Hello World
  • 79
  • 1
  • 6

1 Answers1

0

having a try-catch will prevent failure or system crash, also you get process.uncaughtException() to do something when the system crashes

check below link for more details

https://nodejs.org/api/process.html#process_event_uncaughtexception

r7r
  • 1,440
  • 1
  • 11
  • 19