Error handling is an essential consideration in all applications. You always want to make sure users aren't scared half to death with some unintelligible error message. Furthermore, you never, ever want any server-side errors ever shown in any way to the client, ever!
Not only that, but you'd want to catch any errors that may in effect break your application. Usually employing typical if-then conditionals are the best way to go in dealing with standard errors and controlling program flow. Still, at times prior to critical code execution, you may need further protection, and better overall error handling. However, overusing try/catch exceptions can decrease system performance!
.NET offers its try/catch error handling , where you'd first issue "try" to run the following code, capture any errors that may occur, and display the exception message, then take any appropriate steps to remedy it. Moreover, this error code block further attaches a finally to itself for any final code to execute:
|
Of course, using finally is not mandatory, and doesn't require it being included. For more info read - Handling and Throwing Exceptions and Best Practices for Handling Exceptions.
Further VB error objects available is the On Error Statement, capable of resuming next and going to a preset error handling label via Goto.
Alternatively to assigning custom error pages through IIS's Custom Errors tab, another such method involves our famous web.config file. Invoking the try/catch error blocks do well for code errors, but server errors? Nope, not these. Here we'll use web.config's custom errors nodes :
|
Now all errors are redirected to more friendly error pages, and if you prefer, why not pull in additional error information, and e-mail yourself or the appropriate party when the error occurs.
Don't forget that you may also implement global error handling not dealt with our try/catch code blocks, via your global.asax file's Application_Error method using .NET's System Error codes:
|
Now error handling in .NET, can and should at times be given over to Stored Procedures via the two good methods found in SQL:
-
@@ERROR :
DECLARE @RetValue int
UPDATE database
SET database.dbfield = 'Jimmy'
WHERE dbfield = 'Dimitrios'IF @@ERROR <> 0
BEGIN
PRINT 'An error occurred'
SET @RetValue = @@ERROR
END
ELSE
BEGIN
PRINT 'All OK'
SET @RetValue = '0'
END
RETURN @RetValue
With the @@Error function you declare a variable for the error, return this value at the end and read this client side or print the error through SQL itself. Note an error return of zero (0) indicates no errors at all. - RAISERROR:
Hard-coded error messages:
RAISERROR ('Error Occurred in : %s', 16, 1)
|
Or utilizing the sp_addmessage system stored procedure to produce error messages using the msg_id, as long as the msg_id is over 50000.
RAISERROR (50001, 16, 1, @columnId)
|
Comments