SlideShare a Scribd company logo
Exception Handling in ASP.NET
            MVC
       Presented by Joncash
            12/3/2012



                                1
Outline
• Understanding ASP.NET MVC application Error
  Handling
• How to Create ASP.NET MVC application Error
  Handling
• ASP.NET MVC application Error Handling V.S
  ASP.NET application Error Handling
• ASP.NET MVC application Error Handling with
  ELMAH

                                            2
Understanding ASP.NET MVC
      application Error Handling
• ASP.NET MVC comes with some built-in
  support for exception handling
  through exception filters.
• 4 basic Types of Filters




                                         3
Exception Filters
• Exception filters are run only if an unhandled
  exception has been thrown when invoking an
  action method.
• The exception can come from the following
  locations
  – Another kind of filter (authorization, action, or result
    filter)
  – The action method itself
  – When the action result is executed (see Chapter 12
    for details on action results)

                                                               4
How to Create ASP.NET MVC
       application Error Handling
• Creating an Exception Filter
  – Exception filters must implement the
    IExceptionFilter interface
• Using the Built-In Exception Filter
  – HandleErrorAttribute




                                           5
Example of Using the Built-In
                  Exception Filter
== controller ==
 == controller ==                                == View/Shared/Error.cshtml ==
                                                  == View/Shared/Error.cshtml ==
public class HomeController : :Controller
 public class HomeController Controller          <h1> Here:
                                                  <h1> Here:
  {{                                             Views/Shared/Error.cshmtl</h1 >>
                                                  Views/Shared/Error.cshmtl</h1
     // GET: /Home/
      // GET: /Home/                             <h2> Shared Error</h2 >>
                                                  <h2> Shared Error</h2
     [ HandleError]
      [ HandleError]
     public ActionResult Index()
      public ActionResult Index()
     {{                                          == web.config ==<system.web>
                                                  == web.config ==<system.web>
        throw new Exception( "Index Error" );
         throw new Exception( "Index Error" );
     }}                                          <<customErrors mode =" On" ></c
                                                    customErrors mode =" On" ></c
  }}                                             ustomErrors>
                                                  ustomErrors>
                                                 </system.web>
                                                  </system.web>




                                                                                    6
Accessing the exception details in 
              Error view
• The HandleError filter not only just returns
  the Error view but it also creates and passes
  the HandleErrorInfo model to the view.
• Error View
   @model System.Web.Mvc.HandleErrorInfo
   <h2>Exception details</h2>
   <p>
     Controller: @Model.ControllerName <br>
     Action: @Model.ActionName
     Exception: @Model.Exception
   </p>

                                                  7
HandleErrorInfo
public class HandleErrorInfo
{
  public HandleErrorInfo(Exception exception, string
       controllerName, string actionName);

    public string ActionName { get; }

    public string ControllerName { get; }

    public Exception Exception { get; }
}
                                                       8
Global / local filter
• Global
  == global.asax.cs ==
  protected void Application_Start()
   {
       GlobalFilters.Filters.add(new HandleErrorAttribute());
   }
• Local
   [HandleError]
   public ActionResult Index()

   [HandleError]
   public class HomeController : Controller


                                                                9
HandleErrorAttribute Class
• Namespace: System.Web.Mvc
  Assembly: System.Web.Mvc (in System.Web.Mvc.dll)

• You can modify the default behavior of
  the HandleErrorAttribute filter by setting the following properties:
    – ExceptionType. Specifies the exception type or types that the filter
      will handle. If this property is not specified, the filter handles all
      exceptions.
    – View. Specifies the name of the view to display.
        • default value of Error, so by default, it renders
          /Views/<currentControllerName>/Error.cshtml or
          /Views/Shared/Error.cshtml.
    – Master. Specifies the name of the master view to use, if any.
    – Order. Specifies the order in which the filters are applied, if more than
      one HandleErrorAttribute filter is possible for a method.

                                                                               10
Returning different views for 
             different exceptions
• We can return different views from
  the HandleError filter

[HandleError(Exception ==typeof(DbException), View =="DatabaseError")]
 [HandleError(Exception typeof(DbException), View "DatabaseError")]
[HandleError(Exception ==typeof(AppException), View =="ApplicationError")]
 [HandleError(Exception typeof(AppException), View "ApplicationError")]
public class ProductController
 public class ProductController
{{

}}




                                                                             11
HandleError
• The exception type handled by this filter. It will also
  handle exception types that inherit from the specified
  value, but will ignore all others. The default value is
  System.Exception,which means that, by default, it will
  handle all standard exceptions.
• When an unhandled exception of the type specified by
  ExceptionType is encountered, this filter will set the 
  HTTP result code to 500
• Doesn't catch HTTP exceptions other than 500
   – The HandleError filter captures only the HTTP exceptions
     having status code 500 and by-passes the others.

                                                                12
13
ASP.NET MVC application Error
Handling V.S ASP.NET application Error
              Handling
Handled by ASP.NET             Handled by ASP.NET MVC
[HandleError]                  [HandleError]
public ActionResult            public ActionResult
NotFound()                     InternalError()
{                              {
throw new HttpException(404,   throw new HttpException(500,
"HttpException 404 ");         "HttpException 500 ");
}                              }



                                                          14
ASP.NET MVC application Error
        Handling with ELMAH
• When we use the HandleError filter and
  ELMAH in an application we will confused
  seeing no exceptions are logged by ELMAH,
  it's because once the exceptions are handled 
  by the HandleError filter it sets
  theExceptionHandled property of
  the ExceptionContext object to true and that
  hides the errors from logged by ELMAH.

                                              15
ASP.NET MVC application Error
         Handling with ELMAH
• A better way to overcome this problem is
  extend the HandleError filter and signal to
  ELMAH




                                                16
Example of signal ELMAH to log the
               exception
public class ElmahHandleErrorAttribute: HandleErrorAttribute
{
  public override void OnException(ExceptionContext filterContext)
  {
          var exceptionHandled = filterContext.ExceptionHandled;
          base.OnException(filterContext);

        // signal ELMAH to log the exception
        if (!exceptionHandled && filterContext.ExceptionHandled)

ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);
  }
}

                                            Exception Handling in ASP.NET MVC

                                                                            17
Question
• 了解 MVC Error Handling 機制 ( 可處理的
  錯誤有哪些? 如何設定 Global/Local Error
  Handling ?)
• 如何建立 MCV Error Handling
• 如何創造 MVC Error Handling 與 ASP.NET
  Error Handling 案例
• 在 MVC application 使用 Elmah 要如何正
  確的記錄錯誤

                                      18
References
• [ASP.NET MVC] Error Handling(2) – 在
  Controller  裡 Handling Errors
• Handling in ASP.NET MVC
• Logging Errors with ELMAH in ASP.NET MVC 3
  – Part 4 - (HandleErrorAttribute)
• Pro ASP.NET MVC 3 Framework third edition
  – Adam Freeman and Steven Sanderson
• MSDN HandleErrorAttribute
                                               19

More Related Content

What's hot

Exceptions ref
Exceptions refExceptions ref
Exceptions ref. .
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling sharqiyem
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its HandlingBharat17485
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaPrasad Sawant
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Handling error & exception in php
Handling error & exception in phpHandling error & exception in php
Handling error & exception in phpPravasini Sahoo
 
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lampDEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lampFelipe Prado
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in cMemo Yekem
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception HandlingPrabhdeep Singh
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentArtur Szott
 
Redux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncRedux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncArtur Szott
 

What's hot (20)

Exceptions ref
Exceptions refExceptions ref
Exceptions ref
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
Presentation1
Presentation1Presentation1
Presentation1
 
Built in exceptions
Built in exceptions Built in exceptions
Built in exceptions
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its Handling
 
Exception
ExceptionException
Exception
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
 
Handling error & exception in php
Handling error & exception in phpHandling error & exception in php
Handling error & exception in php
 
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lampDEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in c
 
Exception
ExceptionException
Exception
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenment
 
Redux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncRedux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with Async
 

Similar to Exception handling in asp.net

Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1Shinu Suresh
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desaijinaldesailive
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsRandy Connolly
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...WebStackAcademy
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsLukasz Lysik
 
Exception handling
Exception handlingException handling
Exception handlingzindadili
 
Asp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design PatternAsp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design Patternmaddinapudi
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 
Exceptionhandelingin asp net
Exceptionhandelingin asp netExceptionhandelingin asp net
Exceptionhandelingin asp netArul Kumar
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 
Top 10 Mistakes AngularJS Developers Make
Top 10 Mistakes AngularJS Developers MakeTop 10 Mistakes AngularJS Developers Make
Top 10 Mistakes AngularJS Developers MakeMark Meyer
 

Similar to Exception handling in asp.net (20)

Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation Controls
 
Exception handling
Exception handlingException handling
Exception handling
 
Lecture 20-21
Lecture 20-21Lecture 20-21
Lecture 20-21
 
Chapter 7
Chapter 7Chapter 7
Chapter 7
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 
ASP.MVC Training
ASP.MVC TrainingASP.MVC Training
ASP.MVC Training
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline Internals
 
Asp Net Architecture
Asp Net ArchitectureAsp Net Architecture
Asp Net Architecture
 
Spring 3.0
Spring 3.0Spring 3.0
Spring 3.0
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Asp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design PatternAsp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design Pattern
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
Exceptionhandelingin asp net
Exceptionhandelingin asp netExceptionhandelingin asp net
Exceptionhandelingin asp net
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
Top 10 Mistakes AngularJS Developers Make
Top 10 Mistakes AngularJS Developers MakeTop 10 Mistakes AngularJS Developers Make
Top 10 Mistakes AngularJS Developers Make
 

More from LearningTech

More from LearningTech (20)

vim
vimvim
vim
 
PostCss
PostCssPostCss
PostCss
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection &amp; activator
Reflection &amp; activatorReflection &amp; activator
Reflection &amp; activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 

Recently uploaded

Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...Product School
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupCatarinaPereira64715
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...Sri Ambati
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Product School
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutesconfluent
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...Product School
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...Product School
 

Recently uploaded (20)

Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 

Exception handling in asp.net

  • 1. Exception Handling in ASP.NET MVC Presented by Joncash 12/3/2012 1
  • 2. Outline • Understanding ASP.NET MVC application Error Handling • How to Create ASP.NET MVC application Error Handling • ASP.NET MVC application Error Handling V.S ASP.NET application Error Handling • ASP.NET MVC application Error Handling with ELMAH 2
  • 3. Understanding ASP.NET MVC application Error Handling • ASP.NET MVC comes with some built-in support for exception handling through exception filters. • 4 basic Types of Filters 3
  • 4. Exception Filters • Exception filters are run only if an unhandled exception has been thrown when invoking an action method. • The exception can come from the following locations – Another kind of filter (authorization, action, or result filter) – The action method itself – When the action result is executed (see Chapter 12 for details on action results) 4
  • 5. How to Create ASP.NET MVC application Error Handling • Creating an Exception Filter – Exception filters must implement the IExceptionFilter interface • Using the Built-In Exception Filter – HandleErrorAttribute 5
  • 6. Example of Using the Built-In Exception Filter == controller == == controller == == View/Shared/Error.cshtml == == View/Shared/Error.cshtml == public class HomeController : :Controller public class HomeController Controller <h1> Here: <h1> Here: {{ Views/Shared/Error.cshmtl</h1 >> Views/Shared/Error.cshmtl</h1 // GET: /Home/ // GET: /Home/ <h2> Shared Error</h2 >> <h2> Shared Error</h2 [ HandleError] [ HandleError] public ActionResult Index() public ActionResult Index() {{ == web.config ==<system.web> == web.config ==<system.web> throw new Exception( "Index Error" ); throw new Exception( "Index Error" ); }} <<customErrors mode =" On" ></c customErrors mode =" On" ></c }} ustomErrors> ustomErrors> </system.web> </system.web> 6
  • 7. Accessing the exception details in  Error view • The HandleError filter not only just returns the Error view but it also creates and passes the HandleErrorInfo model to the view. • Error View @model System.Web.Mvc.HandleErrorInfo <h2>Exception details</h2> <p> Controller: @Model.ControllerName <br> Action: @Model.ActionName Exception: @Model.Exception </p> 7
  • 8. HandleErrorInfo public class HandleErrorInfo { public HandleErrorInfo(Exception exception, string controllerName, string actionName); public string ActionName { get; } public string ControllerName { get; } public Exception Exception { get; } } 8
  • 9. Global / local filter • Global == global.asax.cs == protected void Application_Start() { GlobalFilters.Filters.add(new HandleErrorAttribute()); } • Local [HandleError] public ActionResult Index() [HandleError] public class HomeController : Controller 9
  • 10. HandleErrorAttribute Class • Namespace: System.Web.Mvc Assembly: System.Web.Mvc (in System.Web.Mvc.dll) • You can modify the default behavior of the HandleErrorAttribute filter by setting the following properties: – ExceptionType. Specifies the exception type or types that the filter will handle. If this property is not specified, the filter handles all exceptions. – View. Specifies the name of the view to display. • default value of Error, so by default, it renders /Views/<currentControllerName>/Error.cshtml or /Views/Shared/Error.cshtml. – Master. Specifies the name of the master view to use, if any. – Order. Specifies the order in which the filters are applied, if more than one HandleErrorAttribute filter is possible for a method. 10
  • 11. Returning different views for  different exceptions • We can return different views from the HandleError filter [HandleError(Exception ==typeof(DbException), View =="DatabaseError")] [HandleError(Exception typeof(DbException), View "DatabaseError")] [HandleError(Exception ==typeof(AppException), View =="ApplicationError")] [HandleError(Exception typeof(AppException), View "ApplicationError")] public class ProductController public class ProductController {{ }} 11
  • 12. HandleError • The exception type handled by this filter. It will also handle exception types that inherit from the specified value, but will ignore all others. The default value is System.Exception,which means that, by default, it will handle all standard exceptions. • When an unhandled exception of the type specified by ExceptionType is encountered, this filter will set the  HTTP result code to 500 • Doesn't catch HTTP exceptions other than 500 – The HandleError filter captures only the HTTP exceptions having status code 500 and by-passes the others. 12
  • 13. 13
  • 14. ASP.NET MVC application Error Handling V.S ASP.NET application Error Handling Handled by ASP.NET Handled by ASP.NET MVC [HandleError] [HandleError] public ActionResult public ActionResult NotFound() InternalError() { { throw new HttpException(404, throw new HttpException(500, "HttpException 404 "); "HttpException 500 "); } } 14
  • 15. ASP.NET MVC application Error Handling with ELMAH • When we use the HandleError filter and ELMAH in an application we will confused seeing no exceptions are logged by ELMAH, it's because once the exceptions are handled  by the HandleError filter it sets theExceptionHandled property of the ExceptionContext object to true and that hides the errors from logged by ELMAH. 15
  • 16. ASP.NET MVC application Error Handling with ELMAH • A better way to overcome this problem is extend the HandleError filter and signal to ELMAH 16
  • 17. Example of signal ELMAH to log the exception public class ElmahHandleErrorAttribute: HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { var exceptionHandled = filterContext.ExceptionHandled; base.OnException(filterContext); // signal ELMAH to log the exception if (!exceptionHandled && filterContext.ExceptionHandled) ErrorSignal.FromCurrentContext().Raise(filterContext.Exception); } } Exception Handling in ASP.NET MVC 17
  • 18. Question • 了解 MVC Error Handling 機制 ( 可處理的 錯誤有哪些? 如何設定 Global/Local Error Handling ?) • 如何建立 MCV Error Handling • 如何創造 MVC Error Handling 與 ASP.NET Error Handling 案例 • 在 MVC application 使用 Elmah 要如何正 確的記錄錯誤 18
  • 19. References • [ASP.NET MVC] Error Handling(2) – 在 Controller  裡 Handling Errors • Handling in ASP.NET MVC • Logging Errors with ELMAH in ASP.NET MVC 3 – Part 4 - (HandleErrorAttribute) • Pro ASP.NET MVC 3 Framework third edition – Adam Freeman and Steven Sanderson • MSDN HandleErrorAttribute 19

Editor's Notes

  1. The HandleError filter works  only if the &lt;customErrors&gt; section is turned on  in web.config.