Asp.Net Bundle - 如何在缩小失败时引发异常

Aug*_*eto 1 asp.net asp.net-mvc asp.net-bundling

我正在使用Asp.Net MVC 5以及System.Web.Optimization 1.1.0.0中的捆绑和缩小系统:

        bundles.Add(new ScriptBundle("~/angularLibraries").Include(
            ......
            ));
Run Code Online (Sandbox Code Playgroud)

然后渲染Bundle:

@Scripts.Render("~/angularLibraries")
Run Code Online (Sandbox Code Playgroud)

我不时通过在浏览器中打开相应的URL来手动检查我的包的状态,有时我发现它们有错误.例:

/* Minification failed. Returning unminified contents.
(262,145-152): run-time error JS1019: Can't have 'break' outside of loop: break a
(40,297-304): run-time error JS1019: Can't have 'break' outside of loop: break a
 */
Run Code Online (Sandbox Code Playgroud)

因为捆绑机制在缩小失败时返回未分析的内容,所以在我在浏览器中手动打开该捆绑包之前我不知道该错误.

如何在缩小失败时设置Bundling系统以引发异常,以便我能立即意识到错误?

Aug*_*eto 6

找到了解决方案.我创建了一个派生自ScriptBundle的自定义类,并重写了ApplyTransforms方法:

public class CustomScriptBundle : ScriptBundle
{
    public CustomScriptBundle(string virtualPath)
        : base(virtualPath)
    {
    }

    public CustomScriptBundle(string virtualPath, string cdnPath)
        : base(virtualPath, cdnPath)
    {
    }

    public override BundleResponse ApplyTransforms(BundleContext context, string bundleContent, IEnumerable<BundleFile> bundleFiles)
    {
        BundleResponse bundleResponse = base.ApplyTransforms(context, bundleContent, bundleFiles);

        if (bundleResponse.Content.StartsWith("/* Minification failed. Returning unminified contents."))
            ExceptionManager.LogMessage("Minification failed for following bundle: " + context.BundleVirtualPath);

        return bundleResponse;
    }
}
Run Code Online (Sandbox Code Playgroud)

我最后记录了一条消息(收到Elmah发送的电子邮件通知)并且没有抛出异常,因为我默认只在生产时启用了缩小功能,并且应用程序仍将继续正常工作.

如果你抛出异常,你会看到这样的:

在此输入图像描述

此解决方案也适用于StyleBundle.