最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - trycatch block not catching asyncawait error - Stack Overflow

programmeradmin1浏览0评论

I have a simple timeout function which wraps an async function with a timeout to ensure that it fails after a preset amount of time. The timeout function is as follows:

export default async function<T = any>(
  fn: Promise<T>,
  ms: number,
  identifier: string = ""
): Promise<T> {
  let pleted = false;
  const timer = setTimeout(() => {
    if (pleted === false) {
      const e = new Error(`Timed out after ${ms}ms [ ${identifier} ]`);
      e.name = "TimeoutError";
      throw e;
    }
  }, ms);
  const results = await fn;
  pleted = true;
timer.unref();

  return results;
}

I then use this function in this simple code snippet to ensure that the fetch request (using node-fetch implementation) is converted into a text output:

let htmlContent: string;
  try {
    htmlContent = await timeout<string>(
      response.text(),
      3000,
      `waiting for text conversion of network payload`
    );
  } catch (e) {
    console.log(
      chalk.grey(`- Network response couldn\'t be converted to text: ${e.message}`)
    );
    problemsCaching.push(business);
    return business;
  }

When running this code over many iterations, most URL endpoints provide a payload that can be easily converted to text but occasionally one crops up which seems to just hang the fetch call. In these case the timeout does in fact trigger but the TimeoutError that is thrown is NOT caught by the catch block but instead terminates the running program.

I'm a bit baffled. I do use async/await a lot now but I may still have a few rough edges in my understanding. Can anyone explain how I can effectively capture this error and handle it?

I have a simple timeout function which wraps an async function with a timeout to ensure that it fails after a preset amount of time. The timeout function is as follows:

export default async function<T = any>(
  fn: Promise<T>,
  ms: number,
  identifier: string = ""
): Promise<T> {
  let pleted = false;
  const timer = setTimeout(() => {
    if (pleted === false) {
      const e = new Error(`Timed out after ${ms}ms [ ${identifier} ]`);
      e.name = "TimeoutError";
      throw e;
    }
  }, ms);
  const results = await fn;
  pleted = true;
timer.unref();

  return results;
}

I then use this function in this simple code snippet to ensure that the fetch request (using node-fetch implementation) is converted into a text output:

let htmlContent: string;
  try {
    htmlContent = await timeout<string>(
      response.text(),
      3000,
      `waiting for text conversion of network payload`
    );
  } catch (e) {
    console.log(
      chalk.grey(`- Network response couldn\'t be converted to text: ${e.message}`)
    );
    problemsCaching.push(business);
    return business;
  }

When running this code over many iterations, most URL endpoints provide a payload that can be easily converted to text but occasionally one crops up which seems to just hang the fetch call. In these case the timeout does in fact trigger but the TimeoutError that is thrown is NOT caught by the catch block but instead terminates the running program.

I'm a bit baffled. I do use async/await a lot now but I may still have a few rough edges in my understanding. Can anyone explain how I can effectively capture this error and handle it?

Share Improve this question edited Sep 6, 2018 at 5:49 ken asked Sep 6, 2018 at 5:41 kenken 9,01313 gold badges78 silver badges136 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

A thrown error will only be caught if its directly enclosing function has some sort of error handling. Your anonymous function passed to setTimeout is not the async function itself, so the async function won't stop executing if the separate timeout throws after some time:

const makeProm = () => new Promise(res => setTimeout(res, 200));
(async () => {
  setTimeout(() => {
    throw new Error();
  }, 200);
  await makeProm();
  console.log('done');
})()
  .catch((e) => {
    console.log('caught');
  });

This looks like a good time to use Promise.race: pass it the fetch Promise, and also pass it a Promise that rejects after the passed ms parameter:

async function timeout(prom, ms) {
  return Promise.race([
    prom,
    new Promise((res, rej) => setTimeout(() => rej('timeout!'), ms))
  ])
}

(async () => {
  try {
    await timeout(
      new Promise(res => setTimeout(res, 2000)),
      500
    )
   } catch(e) {
      console.log('err ' + e);
   }
})();

This error is happening in a separate call stack, because it's thrown from within a callback. It's totally separate from the synchronous execution flow inside the try / catch block.

You want to manipulate the same promise object from within the timeout or the success callback. Something like this should work better:

return new Promise( ( resolve, reject ) => {
    let rejected = false;
    const timer = setTimeout( () => {
        rejected = true;
        reject( new Error( 'Timed out' ) );
    }, ms ).unref();
    fn.then( result => {
        clearTimeout( timer );
        if ( ! rejected ) {
            resolve( result ) );
        }
    } );
} );

It would probably work just fine without the rejected and clearTimeout too, but this way you ensure that either resolve or reject is called, not both.

You'll notice that I didn't use await or throw anywhere here! If you are having trouble with asynchronous code, it is better to write it using a single style first (all callbacks, or all promises, or all "synchronous" style using await).

This example in particular cannot be written using only await, because you need to have two tasks running at the same time (the timeout and the request). You could probably use Promise.race(), but you still need a Promise to work with.

I will provide some general rule as the answer was already given.

Try/catch is by default synchronous. That means that if an asynchronous function throws an error in a synchronous try/catch block, no error throws.

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>