locked
Using exception filters with ASP.NET Web Pages / Razor RRS feed

  • Question

  • User-745470448 posted

    I'm trying (hoping?) to use exception filtering in a ASP.NET Web Pages / Razor website. I'm using C# 7 with Microsoft.AspNet.Razor 3.27 and Microsoft.AspNet.WebPages 3.2.7, but I'm still getting errors when trying to use the keyword 'when' in a try catch block, like:

    try
    {
       // do something
    }
    catch (Exception ex) when (Log("log an error"))
    {
    
    }

    The error is:

    Error Expected a "{" but found a "when". Block statements must be enclosed in "{" and "}". You cannot use single-statement control-flow statements in CSHTML pages. For example, the following is not allowed:

    @if(isLoggedIn)
    <p>Hello, @user</p>

    Instead, wrap the contents of the block in "{}":

    @if(isLoggedIn) {
    <p>Hello, @user</p>

    Does Web Pages Razor 3.2.7 just not support exception filtering? It looks like it was added to the Razor that's part of .NET Core Razor back in 2015.

    Monday, April 1, 2019 3:54 PM

All replies

  • User1724605321 posted

    Hi tsulli,

    Do you want to use try..catch in razor ? 

    @try
    {
        <div>typical Razor view stuff here...</div>
    }
    catch (Exception ex)
    {
       
    }

    In addition .  i would suggest to learn the tutorial for error handling in razor page :

    https://www.mikesdotnetting.com/article/266/error-handling-in-asp-net-razor-web-pages 

    Best Regards,

    Nan Yu

    Tuesday, April 2, 2019 2:10 AM
  • User-745470448 posted

    I'm familiar with how to use try ... catch in Razor and with the topics discussed on the linked page. I'm asking specifically about using C# 6 exception filtering (the when keyword followed by a method call, as shown in my question) in Razor code blocks. 

    Tuesday, April 2, 2019 12:16 PM
  • User1724605321 posted

    Hi tsilli ,

    That seems a bug in MVC razor page since .net core won't meet this problem .

    Best Regards,

    Nan Yu

    Wednesday, April 3, 2019 2:19 AM
  • User-1038772411 posted

    hii tsulli,

    Please refere the below link , I hope it helps you

    Try with this 

     https://weblogs.asp.net/dixin/c-6-0-exception-filter-and-when-keyword

    Thank you

    Friday, May 31, 2019 6:51 AM