Kuskuren Gudanarwa a cikin Express.js: Dabaru masu inganci da Saƙonnin Amsa

A yayin haɓaka aikace-aikacen, sarrafa kuskure shine muhimmin al'amari don tabbatar da ƙwarewar mai amfani mai santsi da rage matsalolin da ba a zata ba. A cikin Express.js mahalli, kuna da hanyoyi da yawa don magance kurakurai da samar da saƙon amsa masu dacewa ga masu amfani. Ga jagora kan yadda ake cimma wannan:

Amfani Middleware don Gudanar da Kuskuren Duniya

Ƙirƙirar sarrafa kuskuren duniya middleware ta ƙara lambar mai zuwa a ƙarshen app.js ko babban fayil ɗin Express.js aikace-aikacenku.

app.use((err, req, res, next) => {  
  console.error(err.stack);  
  res.status(500).send('Something went wrong!');  
});  

Gudanar da Kurakurai don Musamman Route

A cikin takamaiman route, zaku iya amfani da try block catch don kama kurakurai da samar da saƙon amsa da suka dace.

app.get('/profile/:id', async(req, res) => {  
  try {  
    const user = await getUserById(req.params.id);  
    res.json(user);  
  } catch(error) {  
    res.status(404).send('User not found!');  
  }  
});  

Amfani da Kuskure Tsakanin Middleware

Ƙirƙirar kuskuren tsakiya middleware don ɗaukar kurakuran da suka samo asali daga route.

app.use((req, res, next) => {  
  const error = new Error('Not found');  
  error.status = 404;  
  next(error);  
});  
  
app.use((err, req, res, next) => {  
  res.status(err.status || 500);  
  res.send(err.message || 'Something went wrong');  
});  

Magance Kurakurai Asynchronous

A cikin yanayin sarrafa asynchronous, yi amfani da next hanyar don ƙaddamar da kurakurai zuwa sarrafa kuskuren duniya middleware.

app.get('/data',(req, res, next) => {  
  fetchDataFromDatabase((err, data) => {  
    if(err) {  
      return next(err);  
    }  
    res.json(data);  
  });  
});  

 

Kammalawa

Gudanar da kuskure wani muhimmin sashi ne na Express.js haɓaka aikace-aikacen. Ta amfani da middleware, sarrafa takamaiman kurakurai, da samar da saƙon amsa da suka dace, zaku iya ƙirƙirar ingantaccen ƙwarewar aikace-aikace don masu amfani da ku.