如何覆盖 $exceptionHandler 实现 [英] How to override $exceptionHandler implementation

查看:20
本文介绍了如何覆盖 $exceptionHandler 实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当抛出 javascript 异常时,我们都想做一些额外的事情.

There are some extra things we want to do anytime a javascript exception is thrown.

来自 $exceptionHandler 上的文档:

角度表达式中任何未捕获的异常都委托给此服务.默认实现只是委托给 $log.error ,后者将其记录到浏览器控制台中.

Any uncaught exception in angular expressions is delegated to this service. The default implementation simply delegates to $log.error which logs it into the browser console.

事实上,它说默认实现"让我觉得有一种方法可以为服务提供我们自己的实现,并在抛出异常时做我们想做的事情.我的问题是,你如何做到这一点?我们怎样才能让所有异常都进入这个服务,然后提供我们想要的功能?

The fact that it says "default implementation" makes me think there's a way we can provide our own implementation for the service, and do the stuff we want when an exception is thrown. My question is, how do you do this? How can we keep all exceptions going to this service, but then provide functionality we want to happen?

推荐答案

我发现的另一个选项是通过 $provide.decorator 功能.如果您想将其用作自定义实现的一部分,这将为您提供对原始实现的引用.所以,你可以这样做:

Another option I've found for this is to "decorate" the $exceptionHandler through the $provide.decorator function. This provides you with a reference to the original implementation if you want to use it as part of your custom implementation. So, you can do something like this:

mod.config(function($provide) {
    $provide.decorator("$exceptionHandler", ['$delegate', function($delegate) {
        return function(exception, cause) {
            $delegate(exception, cause);
            alert(exception.message);
        };
    }]);
});

它将执行原始异常处理程序所做的工作,以及自定义功能.

It will do what the original exception handler does, plus custom functionality.

请参阅此更新的小提琴.

这篇关于如何覆盖 $exceptionHandler 实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆