In the UI Code (ASPX), I want to write proper error handling code to display the error in a nice way depending on the error type.
In my case, I see the errors has two main categories:
1. Unexpected errors which you need to dump the full "ex.StackTrace" and this will look very ugly, but is needed so that the developer can locate the source of the error in the code.
2. Expected errors such as incorrect data in a field or record not found ...etc. Such errors are controlled and I will display a nice error message to the user with full details to help resolve the problem. In this case, I only need to display a one-line error without any other details.
Why I am asking for this? This is becuase I realized that any error thrown from the Business Object / Data Access Part, it will always be "DataPortalException". Sometimes, when there is an expected error while in "Data Access" part, I will throw a predefined exception, say eHRMDException(), with custom message. But I find difficulty in catching this error on the UI part, and I want to make sure I am doing the right thing.
I am using the following code template, and I need you help to tell me if this is OK (see the DataPortalException):
Try
theStaffID = Request.QueryString("StaffID")
If SPMSForm.Exists(theStaffID) Then
theSPMSForm = SPMSForm.GetSPMSForm(theStaffID)
Else
theSPMSForm = SPMSForm.NewSPMSForm(theUserCtrlInfoPack)
End If
SaveSPMSFormToSession(theSPMSForm)
theSPMSForm.RenderPDFForm(Response, GetWebRoot, Page.Server.MapPath(".\"))
Response.End()
Catch ex As System.Security.SecurityException
GetMaster.ErrMsg = ex.Message
ClearMedicalCardFormSession()
Catch ex As eHRMDException
GetMaster.ErrMsg = ex.Message
ClearMedicalCardFormSession()
Catch ex As Csla.DataPortalException
If Not ex.BusinessException Is Nothing AndAlso TypeOf (ex.BusinessException) Is eHRMDException Then
GetMaster.ErrMsg = ex.BusinessException.Message
Else
GetMaster.ErrMsg = ex.Message & "<br>" & ex.StackTrace
End If
ClearMedicalCardFormSession()
Catch ex As Exception
GetMaster.ErrMsg = ex.Message & "<br>" & ex.StackTrace
ClearMedicalCardFormSession()
End Try
In the above code, I am checking the type of the BusinessException, and if it is "eHRMDException" which is the custom error I generated, then I will only display the error message as one line, otherwise, I will display the complete StackTrace().
If you have any comment or suggestion to do it in a better way, please let me know.
Tarek.
Copyright (c) Marimer LLC