2008/09/10

asp.net catch all application errors


depois de ler o completissimo artigo em http://www.aspnetresources.com/articles/CustomErrorPages.aspx meti mãos a obra e, basicamente é isto:

no global.asax interceptar o erro na aplicação -> deve de ser código simples para que ele próprio nao gere um erro. Se a escrita de um ficheiro baseado em parâmetros bastante fixos der erro então algo está MESMO mal. Adicionei o chr(13) depois do
para se conseguir ver bem, quer no notpead, quer no browser.

no web.config definir a página "amigável" para o utilizador. Esta página, se possível, deve de ser em HTML puro para não gerar erros.

em baixo apresento o bocado de código

as páginas HTML não estão incluídas neste molho. Para fazer com que as paginas HTML há uma secção no artigo que tem a receita :

  1. Run the IIS Manager
  2. Select a web application
  3. Right click and go to Properties
  4. On the Virtual Directory tab click Configuration
  5. In the Extension column find .aspx, double click and copy the full path to aspnet_isapi.dll. It should be something like C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\«
    aspnet_isapi.dll
  6. Click Add and paste the path in the Executable box
  7. In the Extension box type .html
  8. Make sure Check that file exists is NOT checked
  9. Dismiss all dialogs

----------------

after reading the great article http://www.aspnetresources.com/articles/CustomErrorPages.aspx i tried to do it myself and it was surprisingly easy:

global.asax -> use de application error and write to a file. the code should be plain and simple cause we wouldn't want another error here.
Web.config -> redirect all error to a plain and simple html page so we can avoid almost all errors.

Go down for the coding part.

HTML files are not inluded ins this "friendly error treatment" cause IIS does "sees" them. If you want them to be included follow the article recipe:
  1. Run the IIS Manager
  2. Select a web application
  3. Right click and go to Properties
  4. On the Virtual Directory tab click Configuration
  5. In the Extension column find .aspx, double click and copy the full path to aspnet_isapi.dll. It should be something like C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\«
    aspnet_isapi.dll
  6. Click Add and paste the path in the Executable box
  7. In the Extension box type .html
  8. Make sure Check that file exists is NOT checked
  9. Dismiss all dialogs
---------

global.asax

Dim ctx As HttpContext = HttpContext.Current

Dim exception As Exception = ctx.Server.GetLastError

Dim errorinfo As String = "

" & Now() & "
Offending URL: " + ctx.Request.Url.ToString() + "
Source: " + exception.Source + "
Message: " + exception.Message + "
Stack trace: " + exception.StackTrace

Dim errlog As IO.StreamWriter = System.IO.File.AppendText(Server.MapPath("\") & "\error.log")
errlog.WriteLine(errorinfo.Replace("
", "
" & Chr(13)))
errlog.Flush()
errlog.Close()
errlog.Dispose()


web.config


Sem comentários: