programing

Angular 1.6.0: "Possible unhandled reject" 오류

oldcodes 2023. 2. 23. 23:03
반응형

Angular 1.6.0: "Possible unhandled reject" 오류

우리는 Angular 1.6.0까지 우리에게 도움이 된 약속을 해결하기 위한 패턴을 가지고 있다.

    resource.get().$promise
        .then(function (response) {
        // do something with the response
        }, function (error) {
            // pass the error the the error service
            return errorService.handleError(error);
        });

카르마의 오류를 촉발하는 방법은 다음과 같습니다.

    resourceMock.get = function () {
        var deferred = $q.defer();
        deferred.reject(error);
        return { $promise: deferred.promise };
    };

이제 1.6.0으로 업데이트되면서 Angular는 유닛 테스트(Karma)에서 "Possible unhandled reject" 오류로 인해 거부된 약속에 대해 갑자기 불만을 제기합니다.그러나 우리는 에러 서비스를 호출하는 두 번째 함수로 거부를 처리하고 있습니다.

앵글이 찾는 게 정확히 뭐죠?거절을 어떻게 '처리'하면 좋을까요?

이 코드를 설정에 추가해 보세요.예전에 비슷한 문제가 있었는데 이 해결방법이 효과가 있었어요.

app.config(['$qProvider', function ($qProvider) {
    $qProvider.errorOnUnhandledRejections(false);
}]);

표시된 코드는 호출 전에 발생하는 거부를 처리합니다..then이 경우 두 번째 콜백으로 넘어갑니다..then호출되고 거부 처리는 처리됩니다.

하지만 당신이 전화한 약속이.then성공하고 첫 번째 콜백을 호출합니다.이 콜백이 예외를 슬로우하거나 거부된 약속을 반환하는 경우 두 번째 콜백은 첫 번째 콜백까지 원인 거부 처리를 하지 않기 때문에 이 결과 거부 처리는 처리되지 않습니다.이것이 Promise/A+ 사양을 준수하는 약속 구현과 Angular 약속을 준수하는 방법입니다.

이 문제는 다음 코드로 설명할 수 있습니다.

function handle(p) {
    p.then(
        () => {
            // This is never caught.
            throw new Error("bar");
        },
        (err) => {
            console.log("rejected with", err);
        });
}

handle(Promise.resolve(1));
// We do catch this rejection.
handle(Promise.reject(new Error("foo")));

Promise/A+에도 준거한 노드에서 실행하면 다음과 같은 결과가 나타납니다.

rejected with Error: foo
    at Object.<anonymous> (/tmp/t10/test.js:12:23)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3
(node:17426) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: bar

첫 번째 옵션은 단순히 디세블로 하는 오류를 숨기는 것입니다.errorOnUnhandledRejections권장되는 $qProvider 구성Cengkuru Michael

그러나 이것은 로깅만 끕니다.오류 자체는 그대로 남습니다.

경우 더 나은 해결책은 다음과 같은 방법으로 거절을 처리하는 것입니다..catch(fn)방법:

resource.get().$promise
    .then(function (response) {})
    .catch(function (err) {});

링크:

Angular 1.5.9로 롤백하여 테스트를 재실행하여 문제를 발견.단순한 주입 문제였지만 Angular 1.6.0은 이를 대신 "Possible Unhandled Reject" 오류를 발생시켜 실제 오류를 혼란스럽게 했습니다.

.catch(function () {})에 '코드로'를 할 수 .decorator$exceptionHandler.

이 옵션은 다른 옵션보다 상세하지만 한 곳에서 변경만 하면 됩니다.

angular
    .module('app')
    .config(configDecorators);

configDecorators.$inject = ["$provide"];
function configDecorators($provide) {

    $provide.decorator("$exceptionHandler", exceptionHandler);

    exceptionHandler.$inject = ['$delegate', '$injector'];
    function exceptionHandler($delegate, $injector) {
        return function (exception, cause) {

            if ((exception.toString().toLowerCase()).includes("Possibly unhandled rejection".toLowerCase())) {
                console.log(exception); /* optional to log the "Possibly unhandled rejection" */
                return;
            }
            $delegate(exception, cause);
        };
    }
};

errorOnUnhandledRejections를 끄면 문제를 숨길 수 있지만 오류에 "가능한 거부"를 처리해야 하므로 약속에 캐치만 추가하면 됩니다.

resource.get().$promise
    .then(function (response) {
    // do something with the response
    }).catch(function (error)) {
        // pass the error to the error service
        return errorService.handleError(error);
    });

참고 자료: https://github.com/angular-ui/ui-router/issues/2889

답변은 이쪽에서 확인해 주세요.

Angular 1.6에서 처리되지 않은 거부일 수 있음

문제는 316f60f에서 수정되었으며 수정은 v1.6.1 릴리즈에 포함되어 있습니다.

테스트 실행 중 동일한 동작을 관찰했습니다.제품 코드는 정상적으로 작동하고 테스트에서만 실패하는 것이 이상합니다.

쉬운 은 '시험보다 더하다'를하는 것입니다.catch(angular.noop)당신의 약속에 대한 조롱입니다.위의 예에서는 다음과 같이 표시됩니다.

resourceMock.get = function () {
    var deferred = $q.defer();
    deferred.reject(error);
    return { $promise: deferred.promise.catch(angular.noop) };
};

.6한 후 를 확인해보니 Angular 1.6.7에 하였습니다.$interval.cancel(interval);

하자 문제가 해결되었습니다.angular-mocks(1.7.0)

저는 몇 가지 변경을 한 후에 같은 공지가 떴습니다. 인 것 같다.$http angularjs를 사용한 여러 $q★★★★★★★★★★★★★★★★★★.

난 그것들을 배열로 포장하지 않았어.

$q.all(request1, request2).then(...) 

보다는

$q.all([request1, request2]).then(...)

이걸로 누군가 시간을 절약할 수 있었으면 좋겠어요.

당신의 특별한 상황은 아닐지 모르지만, 저도 비슷한 문제가 있었습니다.

제 경우 angular-i18n을 사용하여 로케일 사전을 비동기적으로 취득하고 있었습니다.문제는 취득한 json 파일의 들여쓰기(스페이스와 탭 혼재)가 올바르지 않다는 것입니다.GET 요청이 실패하지 않았습니다.

움푹 들어간 곳을 고치면 문제가 해결되었다.

언급URL : https://stackoverflow.com/questions/41063947/angular-1-6-0-possibly-unhandled-rejection-error

반응형