3
3
3042018-02-03 20:47:48
JavaScript
304, 2018-02-03 20:47:48

At what level to handle errors in async/await?

For example:
There are 2 modules someRequest, anyRequest.

module.exports = async data => {
  let data = await someReq(data);
  return data.res;
}

module.exports = async data => {
  let data =  await anyReq(data);
  return data.res;
}

In another file, import these modules and use them
let dbreq = require(path_to_DataBaseRequest);
let anyreq = require(path_to_AnyRequest); 

let someFunc = async () => {
    let data = await dbreq();
    let res = await anyreq(data);
    console.log(res)
}
someFunc()

Where should try/catch be used?
At lower levels (in modules someRequest, anyRequest)
module.exports = async data => {
  try{
    let data = await someReq(data);
     return data.res;
  }
  catch(err){
    console.log(err);
  }
}

Or just the top one?
let dbreq = require(path_to_DataBaseRequest);
let anyreq = require(path_to_AnyRequest); 

let someFunc = async () => {
   try{
    let data = await dbreq();
    let res = await anyreq(data);
    console.log(res)
   }
   catch(err){
   console.log(err);
   }
}

someFunc()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Kositsyn, 2018-02-04
@304

In the modules themselves, you do throw if something went wrong. And error handling is done where you call the functions of these modules.
Here is an example of how an array recude is implemented. It throws errors up (to the programmer), and leaves the responsibility for processing to the programmer.

3
304, 2018-02-08
@304

From myself I will add that a record of this kind

let someFunc = async () => {
   try{
    let data = await dbreq();
    let res = await anyreq(data);
    console.log(res)
   }
   catch(err){
   console.log(err);
   }
}

It will not allow us to find out exactly where we caught the error, and process it exactly.
Therefore, there is a record of this kind
let someFunc = async () => {
   try{
     let data = await dbreq();
   catch(err){
     console.log(err);
   }
   try{
     let res = await anyreq(data);
     console.log(res)
   catch(err){
     console.log(err);
   }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question