RickStrahl / Westwind.RazorHosting

Hosting the Razor Runtime outside of ASP.NET/MVC for use in non-Web .NET applications.
144 stars 32 forks source link

Misleading error when model types do not match #5

Closed DioF closed 10 years ago

DioF commented 10 years ago

When one writes a template using a specific model type (not dynamic) and the template is rendered with a different model type, the rendering fails without an exception. The only hint is a misleading text in RazorEngine.ErrorMessage saying

Rendering failed: Template Execution Error: Object reference not set to an instance of an object.

The reason for this is IMO a wrong try ... catch block in RazorEngine, which catches the precise exception and ignores it.

try
{
    dynamic dynInstance = instance;
    dynamic dcontext = context;
    dynInstance.Model = dcontext;
}
catch(Exception ex) 
{
    var msg = ex.Message;
}

msg is not used anymore although it would contain the perfect text

Cannot implicitly convert type 'A' to 'B'. An explicit conversion exists (are you missing a cast?)

I suggest to remove this try ... catch block as the outer try ... catch will do the exception handling the way I would expect.

RickStrahl commented 10 years ago

@DioF - thank you for the report. Looking closer into this there were a few issues here, but yes, simply removing the inner exception block returns the correct error message to the host.

Fixed.

Incidentally before removing that code I found a couple of other issues that were caused by ignoring that error which resulted in the null exception as the effectively the model was passed in as null. This now fixes a few other edge cases.

Thanks again.

It's checked in on the V3.0 branch.

DioF commented 10 years ago

Alright, I've updated my references. Works great! Thanks for your time and work.