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

javascript - TryCatch Decorator not catching errors - Stack Overflow

programmeradmin3浏览0评论

Following tryCatch decorator is unable to catch the error.

const TryCatchWrapper = (target, key, descriptor) => {
  const fn = descriptor.value;
  descriptor.value = (...args) => {
    try {
      fn.apply(this, args);
    } catch (error) {
      console.log('Entered Catch----->');
      const [,, next] = args;
      next(error);
    }
  };
};

Trying to use in the following class-

class CustomerDetails {

  @TryCatchWrapper
  async getCustomerSummary(req, res, next) {
      throw new Error('Whoops!!!');
  }
}

Problem:- 'Entered Catch----->' never gets printed.

Following tryCatch decorator is unable to catch the error.

const TryCatchWrapper = (target, key, descriptor) => {
  const fn = descriptor.value;
  descriptor.value = (...args) => {
    try {
      fn.apply(this, args);
    } catch (error) {
      console.log('Entered Catch----->');
      const [,, next] = args;
      next(error);
    }
  };
};

Trying to use in the following class-

class CustomerDetails {

  @TryCatchWrapper
  async getCustomerSummary(req, res, next) {
      throw new Error('Whoops!!!');
  }
}

Problem:- 'Entered Catch----->' never gets printed.

Share Improve this question asked Nov 30, 2017 at 7:01 Let me seeLet me see 5,0949 gold badges39 silver badges49 bronze badges 1
  • Did you ever get this working? – jackdaw Commented Jul 30, 2018 at 13:55
Add a ment  | 

2 Answers 2

Reset to default 8

It's because getCustomerSummary is an async function. An async function never throws; instead, it returns a promise that gets rejected. (Inside an async function, when you use try/catch around await, that gets turned into promise rejection handling. But in a non-async function calling an async function, that sugar isn't applied.)

You'll need to modify the decorator to look at the return value of the function and, if it's a promise, handle promise rejections.

Actually there is nothing wrong with your approach. You just forgot to await for results from fn.apply and set the descriptor.value as async function. See the example here https://stackblitz./edit/typescript-dycwcg

const TryCatchWrapper = (target, key, descriptor) => {
  const fn = descriptor.value;
  descriptor.value = async (...args) => {
    try {
      await fn.apply(this, args);
    } catch (error) {
      console.log('Entered Catch----->');
      const [,, next] = args;
      next(error);
    }
  };
};
发布评论

评论列表(0)

  1. 暂无评论