ajax application errors developer oversight and tracking errors

30
Ajax Application Ajax Application Errors Errors Developer Oversight and Tracking Errors Developer Oversight and Tracking Errors Presented by Eric Presented by Eric Pascarello Pascarello

Upload: sampetruda

Post on 15-Jan-2015

1.384 views

Category:

Documents


3 download

DESCRIPTION

 

TRANSCRIPT

Page 1: ajax application errors developer oversight and tracking errors

Ajax Application ErrorsAjax Application ErrorsDeveloper Oversight and Tracking ErrorsDeveloper Oversight and Tracking Errors

Presented by Eric PascarelloPresented by Eric Pascarello

Page 2: ajax application errors developer oversight and tracking errors

Author of:Author of:

Page 3: ajax application errors developer oversight and tracking errors

Some Background InfoSome Background Info

HTML/JavaScript HTML/JavaScript Moderator at Moderator at

JavaRanch.com JavaRanch.com

Member since 2001Member since 2001

Ajax Developer at Ajax Developer at market10.commarket10.com

The world’s first job The world’s first job matching sitematching site

Page 4: ajax application errors developer oversight and tracking errors

Developer OversightsDeveloper Oversights

•Are you verifying your data?Are you verifying your data?

•How are you handling server How are you handling server errors?errors?

•Are you using a session?Are you using a session?

•Any ClientSide errors?Any ClientSide errors?

•Did you test your application in Did you test your application in every browser?every browser?

Page 5: ajax application errors developer oversight and tracking errors

Testing JavaScript is Not Testing JavaScript is Not EasyEasy• BrowsersBrowsers

– Firefox, Mozilla, Internet Explorer, Opera, Safari, Firefox, Mozilla, Internet Explorer, Opera, Safari, etcetc

– Multiple Versions (Main releases, betas, etc)Multiple Versions (Main releases, betas, etc)– Different Security SettingsDifferent Security Settings– Different Browser Plug-insDifferent Browser Plug-ins

• Different Operating Systems and PatchesDifferent Operating Systems and Patches

• Different CPUs, RAM, Memory, Multiple Different CPUs, RAM, Memory, Multiple Programs running, Multiple browsers open, Programs running, Multiple browsers open, etc!etc!

Page 6: ajax application errors developer oversight and tracking errors

What you will get from this What you will get from this session:session:

• Learn about some common oversights by Learn about some common oversights by developers.developers.

• Learn about some strange things that occur Learn about some strange things that occur with Ajax applicationswith Ajax applications

• Learn how to track Learn how to track almostalmost all of your all of your clientside errors. clientside errors. – No more wondering why users stop on page 2 of No more wondering why users stop on page 2 of

your application and do not continue on!your application and do not continue on!– Get the basic techniques you can useGet the basic techniques you can use– See how to implement clientside error loggingSee how to implement clientside error logging

Page 7: ajax application errors developer oversight and tracking errors

Developer Oversight #1Developer Oversight #1

• Developers forgetting that the Ajax Developers forgetting that the Ajax response is not perfectresponse is not perfect

• Example #1 from my server log Example #1 from my server log Client Error Message/Detail: ERROR: BAD RESPONSE FROM SERVERClient Error Message/Detail: ERROR: BAD RESPONSE FROM SERVER

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html><html>

<head><head>

<title>User Login</title><title>User Login</title>

Page 8: ajax application errors developer oversight and tracking errors

Oversight #1 SolutionOversight #1 Solution

• Make sure the data is what you Make sure the data is what you expect it to be!expect it to be!

• Validate your dataValidate your data– Use regular expressions to check for Use regular expressions to check for

patternspatterns– Look for key parts of the expressionLook for key parts of the expression– Look for things that do not belongLook for things that do not belong

Page 9: ajax application errors developer oversight and tracking errors

Example #2 for Bad Example #2 for Bad ResponsesResponses

• Pop Up and Cookie Blockers are a Pop Up and Cookie Blockers are a developers problem?developers problem?

• Log from my server:Log from my server:Client Error Message/Detail: ERROR: BAD RESPONSE FROM Client Error Message/Detail: ERROR: BAD RESPONSE FROM SERVER: <script language="JavaScript">SERVER: <script language="JavaScript">

<!-- // Start of AdSubtract JavaScript block; you can ignore this.<!-- // Start of AdSubtract JavaScript block; you can ignore this.

// It is used when AdSubtract blocks cookies or pop-up windows.// It is used when AdSubtract blocks cookies or pop-up windows.

document.iMokie = "cookie blockeddocument.iMokie = "cookie blocked

Page 10: ajax application errors developer oversight and tracking errors

Example #3 for Bad Example #3 for Bad ResponseResponse• Another log from my serverAnother log from my server

Client Error Message/Detail: ERROR: BAD RESPONSE FROM SERVER: Client Error Message/Detail: ERROR: BAD RESPONSE FROM SERVER: <!--//--><script>var PrxLC=new Date(0);var PrxModAtr=0; var <!--//--><script>var PrxLC=new Date(0);var PrxModAtr=0; var PrxInst; if(!PrxInst ) PrxRealOpen=window.open; function PrxOMUp()PrxInst; if(!PrxInst ) PrxRealOpen=window.open; function PrxOMUp(){PrxLC=new Date();}function PrxNW(){ return(this.window);} function {PrxLC=new Date();}function PrxNW(){ return(this.window);} function PrxOpen(PrxOpen(

• So pop up blockers could end up in So pop up blockers could end up in your response from the server! your response from the server! – Reason why logging on the client is goodReason why logging on the client is good– An outside factor you probably would have An outside factor you probably would have

never been able to test for!never been able to test for!

Page 11: ajax application errors developer oversight and tracking errors

Developer Oversight #2Developer Oversight #2

• Sessions Time out!Sessions Time out!– As seen in oversight #1, if session expires As seen in oversight #1, if session expires

login page is returned in the response!login page is returned in the response!

• Sessions do not magically detect Ajax Sessions do not magically detect Ajax Requests and User RequestsRequests and User Requests– Polling can cause session to auto update!Polling can cause session to auto update!– No more session securityNo more session security

Page 12: ajax application errors developer oversight and tracking errors

Oversight #2 SolutionsOversight #2 Solutions

• Session Expired:Session Expired:– Look for a “special key” in the responseLook for a “special key” in the response– If detected reload current pageIf detected reload current page

• Polling Server:Polling Server:– Poll a static file that is not part of sessionPoll a static file that is not part of session– Build your own session managementBuild your own session management

•Save last user action and check with Save last user action and check with polling/page load to see if session expiredpolling/page load to see if session expired

Page 13: ajax application errors developer oversight and tracking errors

Developer Oversight #3Developer Oversight #3

• ServerSide Errors not handled properlyServerSide Errors not handled properly

• If a server encounters an error during If a server encounters an error during the request it will return an error the request it will return an error message or redirect to your error page. message or redirect to your error page. Not good.Not good.

• Oversight #1 with bad response takes Oversight #1 with bad response takes overover

• Leaves user hanging!Leaves user hanging!

Page 14: ajax application errors developer oversight and tracking errors

Oversight #3 SolutionOversight #3 Solution

• Have server log the errorHave server log the error

• Return “Special Key” with ID back to clientReturn “Special Key” with ID back to client– ““Server Error: See log #3141592653589”Server Error: See log #3141592653589”

• In response check for Special KeyIn response check for Special Key– If key is found handle the errorIf key is found handle the error

•Send to error pageSend to error page

•OR Try to make the request againOR Try to make the request again

•OR “Eat” the error if the functionality is not OR “Eat” the error if the functionality is not requiredrequired

Page 15: ajax application errors developer oversight and tracking errors

Developer Oversight #4Developer Oversight #4

• Not Validating the passed Not Validating the passed parameters on the server sideparameters on the server side– SQL InjectionSQL Injection– JavaScript InjectionJavaScript Injection– Value hacksValue hacks– JavaScript ExecutionJavaScript Execution– Bad user input!Bad user input!

• Solution: Validate your data!Solution: Validate your data!

Page 16: ajax application errors developer oversight and tracking errors

2 Errors That Show Up2 Errors That Show Up

• These get posted on Forums all the These get posted on Forums all the time:time:

• Internet Explorer:Internet Explorer:– Automation server can't create object Automation server can't create object

• MozillaMozilla– NS_ERROR_NOT_AVAILABLE NS_ERROR_NOT_AVAILABLE

Page 17: ajax application errors developer oversight and tracking errors

Automation server can't create Automation server can't create objectobject

• Problem comes from ActiveX being Problem comes from ActiveX being disabled. disabled.

• Solution: Use Try catchSolution: Use Try catch

try{ try{ this.req = new ActiveXObject("Microsoft.XMLHTTP"); } this.req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){ catch(e){ this.req = false; this.req = false;} }

Page 18: ajax application errors developer oversight and tracking errors

NS_ERROR_NOT_AVAILABLE NS_ERROR_NOT_AVAILABLE

• Error occurs with reading status codeError occurs with reading status code• quote from quote from https://https://bugzilla.mozilla.org/show_bug.cgi?idbugzilla.mozilla.org/show_bug.cgi?id=238559#c0=238559#c0 • Mozilla calls onload() for all HTTP transactions that succeeded. The only time it Mozilla calls onload() for all HTTP transactions that succeeded. The only time it

calls onerror() is when a network error happened. Inside the onerror handler, calls onerror() is when a network error happened. Inside the onerror handler, accessing the status attribute results in this exception: accessing the status attribute results in this exception:

Error: [Exception... "Component returned failure code: 0x80040111 Error: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.status]" nsresult: (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.status]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: file:///Users/chuck/errtest.html :: anonymous :: line 114" data: no] Source File: file:///Users/chuck/errtest.html :: anonymous :: line 114" data: no] Source File: file:///Users/chuck/errtest.html Line: 114 file:///Users/chuck/errtest.html Line: 114

• Solution: Add try catch around status Solution: Add try catch around status and statusText when reading it for and statusText when reading it for errors!errors!

Page 19: ajax application errors developer oversight and tracking errors

Capturing and Logging the Capturing and Logging the ErrorsErrors

• Types of ErrorsTypes of Errors– Bad response from serverBad response from server– JavaScript Coding ErrorsJavaScript Coding Errors

• Ways of Catching ErrorsWays of Catching Errors– ValidationValidation– window.onerrorwindow.onerror– try{}catch(e){}try{}catch(e){}

Page 20: ajax application errors developer oversight and tracking errors

window.onerrorwindow.onerror

• Event fires for Event fires for almostalmost any JavaScript error any JavaScript error• Contains three arguments: Error Message, Contains three arguments: Error Message,

URL, and Line Number.URL, and Line Number.

var arrErrors = new Array(); var arrErrors = new Array(); window.onerror = function ( strErr, strURL, strLineNumber ) {window.onerror = function ( strErr, strURL, strLineNumber ) { strMess = "URL: " + strURL + "\nline number: " + strLineNumber + strMess = "URL: " + strURL + "\nline number: " + strLineNumber + "\nError Message: " + strErr; arrErrors.push(strMess); "\nError Message: " + strErr; arrErrors.push(strMess); alert(arrErrors.join("\n__________\n\n")); alert(arrErrors.join("\n__________\n\n"));} }

• Basic Example using code above: Basic Example using code above: http://radio.javaranch.com/pascarello/2006/http://radio.javaranch.com/pascarello/2006/01/11/1137003773899.html01/11/1137003773899.html

Page 21: ajax application errors developer oversight and tracking errors

try{} catch(e){}try{} catch(e){}

try{try{ var a = 123;var a = 123; var b = a.indexOf("s");var b = a.indexOf("s");}}catch(e){catch(e){ alert("Name: " + e.name + "\nDesc: " + e.description + "\nMsg: " + alert("Name: " + e.name + "\nDesc: " + e.description + "\nMsg: " +

e.msg); e.msg); }}

Page 22: ajax application errors developer oversight and tracking errors

Sending Error to the serverSending Error to the server

• Ajax RequestAjax Request– Great if error does not effect page Great if error does not effect page

functionality and user supports XHR!functionality and user supports XHR!

• Hidden IframeHidden Iframe– Great if error does not effect page Great if error does not effect page

functionality and user has problems with XHRfunctionality and user has problems with XHR

• Redirect PageRedirect Page– Functionality is hosed, nothing to do but run!Functionality is hosed, nothing to do but run!

Page 23: ajax application errors developer oversight and tracking errors

Basic idea for Basic idea for window.onerrorwindow.onerrorvar arrErrors = new Array();var arrErrors = new Array();window.onerror = function ( strErr, strURL, strLineNumber ) {window.onerror = function ( strErr, strURL, strLineNumber ) { strMess = "URL: " + strURL + "\nline number: " + strMess = "URL: " + strURL + "\nline number: " + strLineNumber + "\nError Message: " + strErr;strLineNumber + "\nError Message: " + strErr; arrErrors.push(strMess);arrErrors.push(strMess); var strErrorParams = "?clientControl=AjaxPolling" +var strErrorParams = "?clientControl=AjaxPolling" + "&clientException=true" +"&clientException=true" + "&URL=" + escape(strURL) +"&URL=" + escape(strURL) + "&lineNum=" + strLineNumber +"&lineNum=" + strLineNumber + "&msg=" + escape(strErr);"&msg=" + escape(strErr); var errorLoader = new net.ContentLoader_Error(var errorLoader = new net.ContentLoader_Error( "../SiteError.aspx" + strErrorParams,"../SiteError.aspx" + strErrorParams, finishErrorRequest,finishErrorRequest, ajaxErrorError,ajaxErrorError, "GET");"GET");}}

Page 24: ajax application errors developer oversight and tracking errors

Basic idea for try catch Basic idea for try catch loggingloggingfunction logTryCatch(id, e){function logTryCatch(id, e){ var strErrorParams = "?clientControl=AjaxPanelUpdater" +var strErrorParams = "?clientControl=AjaxPanelUpdater" + "&clientException=true" +"&clientException=true" + "&URL=" + escape(window.location.href) +"&URL=" + escape(window.location.href) + "&lineNum=" + id +"&lineNum=" + id + "&msg=" + escape(e.name + "-" + e.description + "&msg=" + escape(e.name + "-" + e.description + "-" + e.msg); "-" + e.msg); var errorLoader = new net.ContentLoader_Error(var errorLoader = new net.ContentLoader_Error( "../SiteError.aspx" + strErrorParams,"../SiteError.aspx" + strErrorParams, finishErrorRequest,finishErrorRequest, ajaxErrorError,ajaxErrorError, "GET");"GET");}}

Page 25: ajax application errors developer oversight and tracking errors

Basic idea for bad responseBasic idea for bad response

function logBadResponse(strMessage){function logBadResponse(strMessage){ var strErrorParams = "?var strErrorParams = "?

clientControl=AjaxRSSUpdater" +clientControl=AjaxRSSUpdater" + "&clientException=false" +"&clientException=false" + "&URL=" + escape(window.location.href) +"&URL=" + escape(window.location.href) +

"&msg=" + strMessage); "&msg=" + strMessage); var errorLoader = new net.ContentLoader_Error(var errorLoader = new net.ContentLoader_Error( "../SiteError.aspx" + strErrorParams,"../SiteError.aspx" + strErrorParams, finishErrorRequest,finishErrorRequest, ajaxErrorError,ajaxErrorError, "GET");"GET");}}

Page 26: ajax application errors developer oversight and tracking errors

What you want to send?What you want to send?

• Send as much data as you can!Send as much data as you can!– The URL, form parameters, responseText, js files The URL, form parameters, responseText, js files

that are loaded, browser, OS, etc.that are loaded, browser, OS, etc.• The more information you have to use gives The more information you have to use gives

you a better chance of finding the error. you a better chance of finding the error. – Not as easy as looking at the JavaScript console Not as easy as looking at the JavaScript console

and view source! You need to guess how the user and view source! You need to guess how the user got the error!got the error!

– Error Messages from onerror and catch are plain! Error Messages from onerror and catch are plain! • UndefinedUndefined is the best error message to see in the log! It is the best error message to see in the log! It

gives you so much information to work with! (Note the gives you so much information to work with! (Note the sarcasm)sarcasm)

Page 27: ajax application errors developer oversight and tracking errors

What to do on the server?What to do on the server?

• Obtain the information from the query Obtain the information from the query string or posted form parameters. string or posted form parameters. (Depends on your implementation)(Depends on your implementation)

• Log the error!Log the error!

• When using XHR - send confirmation When using XHR - send confirmation code of success!code of success!

• Display Error Page for bad errorsDisplay Error Page for bad errors

Page 28: ajax application errors developer oversight and tracking errors

How to debug Errors?How to debug Errors?

• Some errors will be easy to solve.Some errors will be easy to solve.• Others can cause you to become bald with Others can cause you to become bald with

bumps on your head!bumps on your head!– Make sure to try to use the browser and OS Make sure to try to use the browser and OS

you recorded.you recorded.– Go to the page in question and mess aroundGo to the page in question and mess around– Use all the information you got from the log.Use all the information you got from the log.– Change browser settings (Security levels!)Change browser settings (Security levels!)– If all else fails – email the user if you are lucky If all else fails – email the user if you are lucky

to know who caused the error and ask them to know who caused the error and ask them what they did!what they did!

Page 29: ajax application errors developer oversight and tracking errors

Where to find me:Where to find me:

– Ajax Forum: Ajax Forum: http://http://www.intelliobjects.com/forums/index.phpwww.intelliobjects.com/forums/index.php – HTML/JavaScript Forum: HTML/JavaScript Forum: http://www.JavaRanch.comhttp://www.JavaRanch.com– My Ajax Blog: My Ajax Blog: http://radio.javaranch.com/pascarellohttp://radio.javaranch.com/pascarello– Ajax In Action: Ajax In Action: http://www.manning.com/cranehttp://www.manning.com/crane

• Manning has author online which is a forum to ask Dave Manning has author online which is a forum to ask Dave Crane and me questions about Ajax In ActionCrane and me questions about Ajax In Action

– Under names of A1ien51 or Pascarello on following Under names of A1ien51 or Pascarello on following message boards/ forumsmessage boards/ forums• ajaxfreaks.com,ajaxforums.net,ajaxgoals.com, google groups ajaxfreaks.com,ajaxforums.net,ajaxgoals.com, google groups

on Ajax, webdeveloper.com, codingforums.comon Ajax, webdeveloper.com, codingforums.com

Page 30: ajax application errors developer oversight and tracking errors

QUESTIONS?QUESTIONS?