try… catch as an expression과 동일

Aug 31 2020

다음과 같은 방법을 찾고 있습니다.

myVar = try {someFunction();} catch (e) {return undefined;} ?? defaultValue;

내가 아는 것은 정확하지 않지만 당신은 아이디어를 얻습니다. 이 작업을 수행하는 우아한 방법이 있는지 궁금했습니다.

답변

2 CertainPerformance Aug 31 2020 at 03:51

현재 할 수있는 최선의 방법은 아마도 IIFE 일 것입니다.

myVar = (() => {
  try {
    return someFunction();
  } catch (e) {
  }
})() ?? defaultValue;
PeterSeliger Aug 31 2020 at 05:43

예를 들어 메소드 수정자를 구현 하면 OP의 의사 코드에 가깝고 짧게 표현할 수 있습니다.afterThrowing

const value = try {someFunction();} catch (e) {return undefined;} ?? defaultValue;

... 그러면 ...

const value = (someFunction.afterThrowing(() => null)()) ?? defaultValue;

... 개념 증명으로 구현 및 예제 코드 ...

// myVar = try {someFunction();} catch (e) {return undefined;} ?? defaultValue;

function throwError() {
  throw (new Error('invocation failure'));
}
function getDate() {
  return Date.now();
}
const defaultValue = '... did throw.'

// expressions as short and as close as one can get
// to what has been ask for ...
//
console.log(
  (getDate.afterThrowing(() => null)()) ?? defaultValue
);
console.log(
  (throwError.afterThrowing(() => null)()) ?? defaultValue
);


// demonstrate capability of the after throwing handler ...
function afterThrowingHandler(error, args) {
  console.log(
    'afterThrowingHandler :: context, error, argsList :',
    this,
    error.toString(),
    Array.from(args)
  );
  return null; // according to the OP's use case.
}

console.log(
  (getDate.afterThrowing(afterThrowingHandler)()) ?? defaultValue
);

console.log(
  (throwError.afterThrowing(

    afterThrowingHandler,
    { biz: 'buzz' }

  )('foo', 'bar', 'baz')) ?? defaultValue
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script>
  (function (Function) {

    const fctPrototype = Function.prototype;
    const FUNCTION_TYPE = (typeof Function);

    function isFunction(type) {
      return (
           (typeof type == FUNCTION_TYPE)
        && (typeof type.call == FUNCTION_TYPE)
        && (typeof type.apply == FUNCTION_TYPE)
      );
    }
    function getSanitizedTarget(target) {
      return ((target != null) && target) || null;
    }

    function afterThrowing/*Modifier*/(handler, target) {
      target = getSanitizedTarget(target);

      const proceed = this;
      return (

        isFunction(handler) &&
        isFunction(proceed) &&

        function () {
          const context = target || getSanitizedTarget(this);
          const args = arguments;

          let result;
          try {
            result = proceed.apply(context, args);

          } catch (exception) {

            result = handler.call(context, exception, args);
          }
          return result;
        }

      ) || proceed;
    }
    // afterThrowing.toString = () => 'afterThrowing() { [native code] }';

    Object.defineProperty(fctPrototype, 'afterThrowing', {
      configurable: true,
      writable: true,
      value: afterThrowing/*Modifier*/
    });

  }(Function));
</script>

어느 날에, 자바 스크립트를 공식적으로 제공하는 경우 난 상관 없어 ... .Function.prototype[before|after|around|afterThrowing|afterFinally]