How can I output errors when using .less programmatically?

戏子无情 提交于 2019-12-18 04:05:43

问题


I've written an ASP.NET MVC action method that receives a .less file name, processes it via Less.Parse(<filename>) and outputs the processed css file.

This works fine as long as the .less code is valid, but if there is an error, dotLess just returns an empty string. So if there is an error processing the file, my action method returns an empty css file.

How can I output an error message with a closer description of the syntax error instead?


回答1:


The dotLess parser traps Exceptions and outputs them to a Logger. The snippet from dotLess's source that performs this is LessEngine.TransformToCss:

public string TransformToCss(string source, string fileName)
{
    try
    {
        Ruleset ruleset = this.Parser.Parse(source, fileName);
        Env env = new Env();
        env.Compress = this.Compress;
        Env env2 = env;
        return ruleset.ToCSS(env2);
    }
    catch (ParserException exception)
    {
        this.Logger.Error(exception.Message);
    }
    return "";
}

Less.Parse has an overload that takes a DotlessConfiguration object, which provides several properties that you can use:

public class DotlessConfiguration
{
    // Properties
    public bool CacheEnabled { get; set; }
    public Type LessSource { get; set; }
    public Type Logger { get; set; }
    public LogLevel LogLevel { get; set; }
    public bool MinifyOutput { get; set; }
    public int Optimization { get; set; }
    public bool Web { get; set; }
}

You will notice that the Logger property is of type Type. Whatever type you supply must implement dotless.Core.Loggers.ILogger:

public interface ILogger
{
    // Methods
    void Debug(string message);
    void Error(string message);
    void Info(string message);
    void Log(LogLevel level, string message);
    void Warn(string message);
}

As we saw in the first snippet, the Error method on the logger will get called when an error is encountered during parsing.

Now, the one sticky point of all this is how exactly an instance of the type that implements ILogger gets instantiated. Internally, dotLess uses an IoC container that is baked into the DLL. Following the method calls, it appears that it will eventually call Activator.CreateInstance to instantiate your ILogger.

I hope this is at least somewhat helpful.




回答2:


I just faced this today in my RequestReduce project. I was getting blank less -> css transforms because there were parse errors that appeared to be going into the ether. Thanks to qes's answer I was able to work out a solution where I could write the errors to the response stream. Here is my dotless.Core.Loggers.ILogger:

public class LessLogger : ILogger
{
    public void Log(LogLevel level, string message)
    {
    }

    public void Info(string message)
    {
    }

    public void Debug(string message)
    {
    }

    public void Warn(string message)
    {
    }

    public void Error(string message)
    {
        Response.Write(message);
    }

    public HttpResponseBase Response { get; set; }
}

I pass this into the Configuration sent to the EngineFactory:

            var engine = new EngineFactory(new DotlessConfiguration
                                               {
                                                   CacheEnabled = false,
                                                   Logger = typeof (LessLogger)
                                               }
                ).GetEngine();

For unit testing purposes I wanted to pass in my HttpResponseBase that would write the error. This is where I felt things getting ugly with some nasty casting to get a reference to my logger:

            ((LessLogger)((LessEngine)((ParameterDecorator)engine).Underlying).Logger).Response = response;

I hope this helps out and if someone knows of a more elegant way to get a reference to the logger, please let me know.




回答3:


You can do this very easily with web.config. In your dotless configuration section, add the following: logger="dotless.Core.Loggers.AspResponseLogger". This will make dotless output the errors instead of blank css.

I've included the following as an example. ("..." represents existing stuff in your web.config). In my example below cache is set to false. This is useful for debugging purposes. It should probably be set to true under normal circumstances.

<configuration>    
     <configSections>
           ...
          <section name="dotless" type="dotless.Core.configuration.DotlessConfigurationSectionHandler,dotless.Core" />
      </configSections>

      <dotless minifyCss="false" cache="false" 
            logger="dotless.Core.Loggers.AspResponseLogger" />
       ...    
</configuration>    



回答4:


I am using a wrapper class around dotless, as follows:

public class LessParser : IStylizer
{
    public string ErrorFileName { get; private set; }
    public int ErrorLineNumber { get; private set; }
    public int ErrorPosition { get; private set; }
    public string ErrorMessage { get; private set; }

    string IStylizer.Stylize(Zone zone)
    {
        ErrorFileName = zone.FileName;
        ErrorLineNumber = zone.LineNumber;
        ErrorPosition = zone.Position;
        ErrorMessage = zone.Message;

        return String.Empty;
    }

    public string Compile(string lessContent, string lessPath)
    {
        var lessEngine = new EngineFactory(new DotlessConfiguration
        {
            CacheEnabled = false,
            DisableParameters = true,
            LogLevel = LogLevel.Error,
            MinifyOutput = true
        }).GetEngine();

        lessEngine.CurrentDirectory = lessPath;

        /* uncomment if DisableParameters is false
        if (lessEngine is ParameterDecorator)
            lessEngine = ((ParameterDecorator)lessEngine).Underlying;
        */

        /* uncomment if CacheEnabled is true
        if (lessEngine is CacheDecorator)
            lessEngine = ((CacheDecorator)lessEngine).Underlying;
        */

        ((LessEngine)lessEngine).Parser.Stylizer = this;

        return lessEngine.TransformToCss(lessContent, null);
    }

    public FileInfo SyncCss(FileInfo lessFile)
    {
        var cssFile = new FileInfo(
            lessFile.FullName.Substring(0, lessFile.FullName.Length - lessFile.Extension.Length) + ".css");

        if (!cssFile.Exists || cssFile.LastWriteTimeUtc < lessFile.LastWriteTimeUtc)
        {
            string cssContent = Compile(ReadFileContent(lessFile), lessFile.DirectoryName);

            if (String.IsNullOrEmpty(cssContent))
                return null;

            using (var stream = cssFile.Open(FileMode.Create))
            using (var writer = new StreamWriter(stream, Encoding.UTF8))
            {
                writer.Write(cssContent);
            }
        }

        return cssFile;
    }

    public string ReadFileContent(FileInfo file)
    {
        using (var reader = file.OpenText())
        {
            return reader.ReadToEnd();
        }
    }
}

The trick is to use own implementation of IStylizer interface that is called upon encountering a parse error to format the resulting error message. This allows us to capture discrete pieces of the error, unlike implementation of ILogger interface where the error is already a formatted text.

var parser = new LessParser();
var lessFile = new FileInfo("C:\\temp\\sample.less"));
var cssFile = parser.SyncCss(lessFile);

if (cssFile != null)
    Console.WriteLine(parser.ReadFileContent(cssFile));
else
    Console.WriteLine("Error '{3}' in {0}, line {1}, position {2}",
        parser.ErrorFileName, parser.ErrorLineNumber, parser.ErrorPosition, parser.ErrorMessage);



回答5:


For the benefit of others, @tony722's solution works if you simply reference .less files from your pages.

But if you call Less.Parse directly, this method will write any error into Response:

var lessConfig = new DotlessConfiguration { Logger = typeof(AspResponseLogger) };
string css = Less.Parse(someInput, lessConfig);



回答6:


This logs to output window in VS:

var config = dotless.Core.configuration.DotlessConfiguration.GetDefault();
config.Logger = new dotless.Core.Loggers.DiagnosticsLogger(dotless.Core.Loggers.LogLevel.Debug).GetType();
config.MinifyOutput = minified;
css= Less.Parse(css, config);


来源:https://stackoverflow.com/questions/4798154/how-can-i-output-errors-when-using-less-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!