Tracing, Logging, and Error Handling MacDonald Ch. 8 MIS 424 MIS 424 Professor Sandvig Professor...

Preview:

Citation preview

Tracing, Logging, and Tracing, Logging, and Error HandlingError Handling

MacDonald Ch. 8MacDonald Ch. 8

MIS 424

Professor Sandvig

TodayToday

Error HandlingError Handling ObjectiveObjective IIS handlersIIS handlers .NET handlers.NET handlers

• Try Catch blockTry Catch block Exception ClassException Class

• Page-level trappingPage-level trapping• Application-level trappingApplication-level trapping

Global.asaxGlobal.asax Web.configWeb.config

Error HandlingError Handling Goal:Goal:

User NEVER sees yellow screen!!User NEVER sees yellow screen!!• Handle errors gracefullyHandle errors gracefully• Example: Example: WWU, , ThinkGeek

Implementation:Implementation:1.1. Robust programmingRobust programming

Validate all user inputsValidate all user inputs Handle foreseeable problemsHandle foreseeable problems

2.2. Trap all errorsTrap all errors Handle gracefullyHandle gracefully

Error PagesError Pages Log errorsLog errors

Error HandlingError Handling

A good programmer is someone who A good programmer is someone who always looks both ways before crossing a always looks both ways before crossing a one-way street.one-way street.

Doug LinderDoug Linder

systems administratorsystems administrator

Error Handling - IISError Handling - IIS

Incorrect URLs may not reach .NETIncorrect URLs may not reach .NET Examples:Examples:

404 error handled by IIS handled by IIS 404 error handled by .NET handled by .NET

Request does not reach .NETRequest does not reach .NET IIS has dozens of error pagesIIS has dozens of error pages

May edit pages & routing rulesMay edit pages & routing rules

IISIIS

.NET.NET

Request reaches .NETRequest reaches .NET Extension: .aspx, asmx, etc.Extension: .aspx, asmx, etc.

Two options:Two options: Handle Programmatically Handle Programmatically web.config redirectweb.config redirect

ASP.NET Error Handling ToolsASP.NET Error Handling Tools

Catch errors at three levels:Catch errors at three levels:1.1. Line: Line:

Try...Catch…Finally blocksTry...Catch…Finally blocks

2.2. Page: Page: Page_error()Page_error()

3.3. Application:Application:Global.asaxGlobal.asax

Line-level Error HandlingLine-level Error Handling

Try Catch BlockTry Catch Block

Wrap high-risk codeWrap high-risk code Database, web servicesDatabase, web services All code that interacts with external dataAll code that interacts with external data

BenefitsBenefits Provide handlersProvide handlers

• Graceful responseGraceful response• Log errorLog error

Continue code executionContinue code execution Easy to implementEasy to implement

Try Catch Block SyntaxTry Catch Block Syntax

trytry{{ // // problematic codeproblematic code}}catch (Exception e)catch (Exception e){{ // // error handler codeerror handler code}}

Try CatchTry Catch

Can trap by type of exceptionCan trap by type of exception Trap specific first, then generalTrap specific first, then general

Syntax:Syntax:Catch objEx as FormatExceptionCatch objEx as FormatException

{ handler }{ handler }

Catch objEx as OleDbExceptionCatch objEx as OleDbException{ Handler }{ Handler }

Catch objEx as ExceptionCatch objEx as Exception{ Handler }{ Handler }

Exception ClassException Class

Exception object thrown when exception Exception object thrown when exception occursoccurs

Contains info about problemContains info about problem Two flavors:Two flavors:

General (General (exception base class)) Specific (Specific (sqlException class))

Exception ClassException Class

Can also customize exceptionsCan also customize exceptions Provide specific informationProvide specific information

Select appropriate exception and add Select appropriate exception and add custom messagecustom message List of exceptions

Example: Dog class (from 324)Example: Dog class (from 324)

Exception ClassException Class

Set dog weight:Set dog weight:

Try Catch BlockTry Catch Block

Where:Where: Catch in .aspx pageCatch in .aspx page Errors will bubble upErrors will bubble up Provide user with nice messageProvide user with nice message Log errorLog error

Exception HandlingException Handling

Exceptions typesExceptions types Listed in MSDN documentationListed in MSDN documentation

• System.Data.SqlClient System.Data.SqlClient SqlException Class

Try CatchTry Catch Example: Example: source, , output WriteErrorLog.cs

Page Level error trappingPage Level error trapping

Catches unhandled exceptions on PageCatches unhandled exceptions on Page

void Page_Error()void Page_Error()

{{

//handle error (write to log, redirect, etc.)//handle error (write to log, redirect, etc.)

}}

Example: Example: source, , output

Page_ErrorPage_Error

LimitationLimitation Page execution is terminatedPage execution is terminated Labels not displayedLabels not displayed User sees text error messageUser sees text error message Graceful response:Graceful response:

• Redirect user to an error pageRedirect user to an error page

Better choice:Better choice:• Handle at application level Handle at application level

Application LevelApplication Level

Catches all unhandled exceptionsCatches all unhandled exceptions Including 404sIncluding 404s

Examples: Amazon, NetflixExamples: Amazon, Netflix

Two options:Two options: Global.asaxGlobal.asax Web.Config fileWeb.Config file

Application LevelApplication Level

Global.asaxGlobal.asax Handles application eventsHandles application events

Application startApplication start Application endApplication end Session startSession start Session endSession end Application_Error()Application_Error()

UnhandledError.aspx source, outputUnhandledError.aspx source, output

Application LevelApplication Level

Web.configWeb.config Last in lineLast in line

Redirects user to an error pageRedirects user to an error page Syntax:Syntax:

<customErrors defaultRedirect="http://..." mode="On"> <customErrors defaultRedirect="http://..." mode="On">

<error statusCode="404" redirect="filenotfound.htm" /><error statusCode="404" redirect="filenotfound.htm" />

</customErrors> </customErrors>

web.configweb.config

CustomErrors sectionCustomErrors section Redirect to error pageRedirect to error page Can configure different pages for different Can configure different pages for different

error codeserror codes Set on individual foldersSet on individual folders Documentation: web.configDocumentation: web.config

Application LevelApplication Level

Web.configWeb.config Disadvantage: cannot get error details for logDisadvantage: cannot get error details for log

Global.asax is better optionGlobal.asax is better option Error details accessibleError details accessible

SummarySummary

Error TrappingError Trapping ObjectivesObjectives

• Handle exceptions gracefullyHandle exceptions gracefully• Record details in log fileRecord details in log file

3 Levels3 Levels

1.1. Line - Try Catch BlockLine - Try Catch Block

2.2. Page - Page_Error()Page - Page_Error()

3.3. ApplicationApplication Global.asax Application_ErrorGlobal.asax Application_Error web.configweb.config

Recommended