Augusto Barreto
Augusto Barreto

Reputation: 3695

Asp.Net Bundle - How to raise exception when minification fails

I'm using Asp.Net MVC 5 and the bundling and minification system from System.Web.Optimization 1.1.0.0:

        bundles.Add(new ScriptBundle("~/angularLibraries").Include(
            ......
            ));

and then to render the Bundle:

@Scripts.Render("~/angularLibraries")

From time to time I manually check the state of my bundles by opening the corresponding url in the browser, and sometimes I find them with errors. Example:

/* 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
 */

Because the bundling mechanism returns the unminified contents when the minification fails, I'm unaware of the error until I manually open that bundle in a browser.

How can I setup the Bundling system to raise an exception when minification fails so I can immediately be aware of the error?

Upvotes: 1

Views: 1058

Answers (1)

Augusto Barreto
Augusto Barreto

Reputation: 3695

Found a solution. I have created a custom class that derives from ScriptBundle and overrides the method 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;
    }
}

I ended up logging a message (an receiving an email notification from Elmah) and not throwing an exception because I have minification enabled by default only on production, and the app will continue working ok anyway.

If you throw an exception, you'll see it like this:

enter image description here

This solution is also applicable for StyleBundle.

Upvotes: 6

Related Questions