SlideShare uma empresa Scribd logo
1 de 19
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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
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
 

Semelhante a 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
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java 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
 

Mais de LearningTech

Mais de 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
 

Último

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 

Último (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 

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

Notas do Editor

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