Wrox Programmer Forums
ASP.NET 1.0 and 1.1 Basics ASP.NET discussion for users new to coding in ASP.NET 1.0 or 1.1. NOT for the older "classic" ASP 3 or the newer ASP.NET 2.0.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the ASP.NET 1.0 and 1.1 Basics section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
Old November 18th, 2003, 07:57 PM
Authorized User
Join Date: Oct 2003
Posts: 12
Thanks: 0
Thanked 0 Times in 0 Posts
Default Catching a SQLException error

I'm building out a SQL server based application using ASP.NET as an intranet application. Constraints we have on the tables mean if a user doesn't use the proper format or uses an invalid data type, the System.Data.SqlClient.SqlException class will return an error back to the requesting page. How can I catch the error and present it in an aesthetically pleasing way to the user instead of

System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'LIFTED_DATE', table 'InventoryControlSystem.dbo.KM_BOL_RANGE'; column does not allow nulls. INSERT fails.
The statement has been terminated.
at System.Data.SqlClient.SqlCommand.ExecuteReader(Com mandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at DreamweaverCtrls.DataSet.DoInit()

Which is obscured behind a graphic and has to be cut and pasted to Wordpad in order to be read. Can I filter this error and return a messagebox of some sort?



Old November 19th, 2003, 10:57 AM
planoie's Avatar
Friend of Wrox
Join Date: Aug 2003
Posts: 5,407
Thanks: 0
Thanked 16 Times in 16 Posts

Put your database calls inside of a Try..Catch block. You can then "Catch" any errors that you would expect to see:

    'Make SQL calls here
Catch e As System.Data.SqlClient.SqlException
    'Handle System.Data.SqlClient.SqlException here
    'you can access the exception message here to give the user feedback
Catch e As SystemException
    'You can have many Catches. They should be ordered from most to least specific.
    'Do stuff here that always needs to be done
    'like closing the database connection
End Try

Work smarter, not harder.
Old November 19th, 2003, 07:26 PM
Authorized User
Join Date: Oct 2003
Posts: 12
Thanks: 0
Thanked 0 Times in 0 Posts

Thanks a lot. I got that to successfully work!

Old January 14th, 2008, 01:21 PM
Authorized User
Join Date: Dec 2007
Posts: 11
Thanks: 0
Thanked 0 Times in 0 Posts

Using this code block, how would one direct a user to an error message that is embedded in a .asp page. Rather than show a person the ugly exception message, I's like to show something more user friendly. Any suggestions?

Old January 14th, 2008, 01:39 PM
Wrox Author
Join Date: Oct 2005
Posts: 4,104
Thanks: 1
Thanked 64 Times in 64 Posts
Send a message via AIM to dparsons

You can do a couple of things:

In the Global.asax you can use the Application_OnError event to redirect a user to a custom error page using:
HttpContext.Current.Server.Response.Redirect("some page.aspx")

Or you can do something like
bool isError = false;
catch(Exception ex)
 isError = true;
 //close connections
 if(isError) { Response.Redirect("somepage.aspx"); }


================================================== =========
Read this if you want to know how to get a correct reply for your question:
================================================== =========
.: Wrox Technical Editor :.
Wrox Books 24 x 7
================================================== =========
Old January 14th, 2008, 03:14 PM
Friend of Wrox
Join Date: Jul 2003
Posts: 599
Thanks: 6
Thanked 3 Times in 3 Posts

It would really be much easier just to validate the data before the error using the same logic that others have presented in a Try/Catch block:

            If Not IsNumeric(txtCompPS.Text) Then
                Throw New Exception("Only numbers are allowed for PS quantity.")
            End If
            Session("Alert") = ex.Message
            If Len(Session("Alert")) = 0 Then
                Session("Confirm") = "[Any confirmation message you want]."
            End If
End Try

Then on the front page I have:

<%@ Register TagPrefix="include" TagName="Alert" src="../include/alert.ascx" %>
<%@ Register TagPrefix="include" TagName="Confirm" src="../include/confirm.ascx" %>

before the <head></head> tags.

And in the body:

<include:Alert ID="Alert" Runat="server" />
<include:Confirm ID="Confirm" Runat="server" />

Alert page:

<%@ Control Language="vb" AutoEventWireup="false" Codebehind="alert.ascx.vb" Inherits="extranet.include_alert" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<table cellpadding="0" cellspacing="5" class="alert" id="tblAlert" runat="server">
        <td class="alert">
            <img border="0" src="../images/icons/alert.gif" width="16" height="16" /><br />
        <td width="100%" class="alert">
            <asp:Literal ID="litAlert" Runat="server" /><br />
    <tr id="tdrOptions" runat="server">
        <td class="alert_options">
            <br />
        <td class="alert_options">
            <asp:Literal ID="litOptions" Runat="server" /><br />

Alert Code behind:

Inherits System.Web.UI.UserControl

    Private _Alert As String
    Private _Options As String

    Protected tblAlert As HtmlTable
    Protected litAlert As Literal
    Protected tdrOptions As HtmlTableRow
    Protected litOptions As Literal

Private Sub Page_Prerender(ByVal Sender As Object, ByVal e As EventArgs) Handles MyBase.PreRender
        _Alert = Session("Alert")
        _Options = Session("Options")
        If Len(_Alert) = 0 Then
            tblAlert.Visible = False
            tblAlert.Visible = True
            litAlert.Text = _Alert
            If Len(_Options) = 0 Then
                tdrOptions.Visible = False
                tdrOptions.Visible = True
                litOptions.Text = _Options
            End If
            Session("Alert") = ""
            Session("Options") = ""
        End If
    End Sub

Similar Threads
Thread Thread Starter Forum Replies Last Post
InitializeCulture causing Sqlexception Error... greglh BOOK: ASP.NET 2.0 Website Programming Problem Design Solution ISBN: 978-0-7645-8464-0 2 March 14th, 2008 11:16 AM
catching error darkhalf Javascript 4 December 14th, 2005 01:44 PM
SqlException error akibaMaila VB.NET 2002/2003 Basics 3 August 25th, 2005 09:14 AM
Error catching and throwing - code rjp Access VBA 1 August 25th, 2004 08:32 PM
catching error fyeojo VS.NET 2002/2003 4 August 13th, 2003 08:29 PM

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.