Data Access  «Prev  Next»

Lesson 9Defensive programming: handling errors
Objective Include general error-handling code in a Razor Page backed by SQL Server.

Defensive Programming: Handling Errors

Every example this module has built, from the first query in Lesson 1 through last lesson's reader loop, has quietly assumed the connection opens, the query runs, and the database returns exactly what was expected. A real Web application can't make that assumption. The connection can fail, the query can violate a constraint, the server can simply be too busy to answer in time, and none of that means the application itself is broken. It means the application needs to plan for the moment something goes wrong, the same way it already plans for the moment everything goes right.

Handling errors in a database-backed Web application isn't fundamentally different from handling errors anywhere else: anticipate what could go wrong, and add the logic to catch it and respond sensibly. The typical database-related failures worth planning for are the same three VirtualBookShelf's own pages are exposed to on every request:
  • A failure to connect to the database at all, something SqlConnection.OpenAsync can throw before a single query ever runs.
  • A failure the database itself reports back, a constraint violation, a timeout, a deadlock, surfaced through SqlException when ExecuteReaderAsync or ExecuteNonQueryAsync runs.
  • A failure that has nothing to do with SQL Server at all, a missing configuration value, a null reference, caught by a broader, more general handler as a last resort.

Where These Failures Actually Come From

None of these failures are exotic. A network hiccup between the application and the database server, a hardware fault on either end, a security or permissions problem, too many other connections already competing for the server's attention, or, rarer but real, a corrupted database, can each produce exactly the kind of failure the layers in this lesson are built to catch. None of them are the application's fault, and none of them are preventable from inside the application's own code; what's preventable is leaving the application with no plan for when one of them happens.

From On Error Resume Next to try/catch: Two Different Ideas, Not Two Spellings of One

The legacy version of this lesson used VBScript's On Error Resume Next statement to keep a page from crashing outright:

<%
Sub ErrorHandler(num, desc, src)
    Response.Write("Error: " & num & "<BR>")
    Response.Write("Description: " & desc & "<BR>")
    Response.Write("Generated by: " & src)
End Sub

On Error Resume Next
Conn.Open "virtualbook"
querystring = "SELECT CustomerID, FirstName, LastName, Email FROM Customer"
Set RS = Conn.Execute(querystring)

If Err.number <> 0 Then
    Call ErrorHandler(Err.number, Err.description, Err.source)
End If
%>
It's tempting to call this the same idea as a modern try/catch block, just older syntax, but the two don't actually work the same way, and the difference is worth stating plainly rather than papering over. On Error Resume Next doesn't jump anywhere when an error occurs; it simply tells VBScript to suppress the runtime error and keep running the very next line, as if nothing happened. The program only finds out something went wrong afterward, by explicitly checking whether Err.number is nonzero. Nothing stops a developer from forgetting that check, in which case the error is silently swallowed and the program continues on with whatever partial state it was left in.

A try/catch block works the other way around. The instant an exception is thrown, control jumps immediately to a matching catch block, no manual flag to remember to check, and no way to accidentally continue past a failure without handling it first. Both approaches exist so a program can survive an error without crashing outright, which is the right-level similarity to draw between them, but one is "continue, then check," and the other is "stop, then handle." Treating them as interchangeable syntax for the same mechanism would be its own small error.

Catching the Error Before It Ever Reaches ASP.NET: TRY...CATCH in SQL Server

The first and often best place to catch a database error is inside the database itself, before SQL Server ever hands anything back to the C# code waiting on the other end of the connection. A stored procedure wrapped in BEGIN TRY/BEGIN CATCH, with SET XACT_ABORT ON at the top, rolls back automatically if any statement inside the transaction fails, rather than leaving a half-applied change and an open transaction behind:

CREATE OR ALTER PROCEDURE dbo.usp_UpdateCustomerEmail
    @CustomerID INT,
    @NewEmail NVARCHAR(256)
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    BEGIN TRY
        BEGIN TRANSACTION;

        UPDATE Customer
        SET Email = @NewEmail
        WHERE CustomerID = @CustomerID;

        IF @@ROWCOUNT = 0
            THROW 50001, 'The specified CustomerID does not exist.', 1;

        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        IF XACT_STATE() <> 0
            ROLLBACK TRANSACTION;

        THROW;
    END CATCH
END;
GO
XACT_STATE() tells the CATCH block whether the transaction is still committable (1) or doomed (-1) before attempting a rollback; rolling back an already-doomed transaction would itself raise an error, so checking first avoids compounding one failure with another. THROW, used with no arguments inside the CATCH block, re-raises the original error exactly as SQL Server generated it, number, severity, message, and line number intact, rather than losing that detail the way the older RAISERROR statement sometimes did. SET XACT_ABORT ON is worth keeping on by habit in any procedure that modifies data inside a transaction; it's a genuinely good general-purpose safeguard, independent of any particular SQL Server feature, that keeps a failed statement from leaving a transaction open and its locks held longer than necessary.

Inspecting SqlException in the Page Model

Back in the C# `PageModel`, that stored procedure is called exactly the way Lesson 3 established, through `CommandType.StoredProcedure`, with the error handling built around catching `SqlException` specifically, before falling back to a broader `Exception` catch for anything that isn't a SQL Server error at all. An injected `ILogger` records the full technical detail server-side, number, procedure, line number, before anything reaches the visitor:

private readonly ILogger<CustomerEditModel> _logger;

public CustomerEditModel(ILogger<CustomerEditModel> logger)
{
    _logger = logger;
}

public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }

    using SqlConnection connection = new(connectionString);
    SqlCommand command = new("dbo.usp_UpdateCustomerEmail", connection)
    {
        CommandType = CommandType.StoredProcedure
    };
    command.Parameters.AddWithValue("@CustomerID", CustomerID);
    command.Parameters.AddWithValue("@NewEmail", Email);

    try
    {
        await connection.OpenAsync();
        await command.ExecuteNonQueryAsync();
        return RedirectToPage("./Index");
    }
    catch (SqlException sqlEx)
    {
        _logger.LogError(sqlEx,
            "SQL error {Number} in {Procedure} at line {LineNumber}: {Message}",
            sqlEx.Number, sqlEx.Procedure, sqlEx.LineNumber, sqlEx.Message);

        foreach (SqlError err in sqlEx.Errors)
        {
            switch (err.Number)
            {
                case 2601:
                case 2627:
                    ModelState.AddModelError("Email",
                        "That email address is already registered to another customer.");
                    break;
                case 547:
                    ModelState.AddModelError(string.Empty,
                        "The update failed because it violates a data integrity rule.");
                    break;
                case 1205:
                    ModelState.AddModelError(string.Empty,
                        "The server is busy processing another request. Please try again.");
                    break;
                case -2:
                    ModelState.AddModelError(string.Empty,
                        "The database query timed out. Please try again.");
                    break;
                case 50001:
                    ModelState.AddModelError(string.Empty, err.Message);
                    break;
                default:
                    ModelState.AddModelError(string.Empty,
                        "A database error occurred while saving your changes.");
                    break;
            }
        }
        return Page();
    }
    catch (Exception ex)
    {
        _logger.LogCritical(ex, "Unexpected error updating CustomerID {CustomerID}", CustomerID);
        ModelState.AddModelError(string.Empty, "An unexpected system error occurred.");
        return Page();
    }
}
Ordering the `catch` blocks this way, most specific first, matters: a `catch (SqlException)` placed after a `catch (Exception)` would never run at all, since the broader type would already have matched. Logging the two cases at different severities, `LogError` for a known SQL Server failure, `LogCritical` for something unanticipated entirely, also means whatever logging destination this application already writes to can distinguish "a visitor hit a constraint we expected" from "something happened we didn't plan for," without needing separate code to tell them apart later. The `switch` over `SqlError.Number` is where Err.number's legacy role actually survives into the modern version, not as a flag to check after the fact, but as the specific detail a catch block already has in hand the moment it runs. `2601` and `2627` both indicate a duplicate value rejected by a unique index or primary key, exactly what a duplicate email address would trigger; `547` covers a foreign key or check constraint violation; `1205` means this call lost out as the victim of a deadlock; `-2` is `SqlException`'s own signal for a client-side command timeout; and anything `50000` or above is a custom error, exactly the kind the stored procedure's own `THROW 50001` raises. Everything that doesn't match a known number falls through to a safe, generic message, never the raw SQL Server text itself.

Rendering the Errors Safely in the View

Concatenating raw error text straight into the rendered HTML risks exposing table names, column names, or other schema details that have no business reaching a visitor's browser. The `ModelState` errors added above render instead through the same Tag Helpers Lessons 4, 6, and 7 already established:

<form method="post">
    <div asp-validation-summary="ModelOnly" class="error-summary" role="alert"></div>
    <input type="hidden" asp-for="CustomerID" />
    <label asp-for="Email">Email Address:</label>
    <input asp-for="Email" type="email" />
    <span asp-validation-for="Email" class="field-error"></span>
    <button type="submit">Save Changes</button>
</form>
`asp-validation-summary="ModelOnly"` renders the general, page-level messages added with `ModelState.AddModelError(string.Empty, ...)`, the deadlock, timeout, and constraint-violation cases above; `asp-validation-for="Email"` renders the field-specific message tied directly to the `Email` input, the duplicate-address case. Either way, what reaches the browser is the sanitized message this lesson's `switch` statement chose, never SQL Server's own error text.

A Global Safety Net for Everything Else

Every error handled so far assumed a `try`/`catch` block was actually there to catch it. A page with no local handling at all, or an exception thrown somewhere outside any `try` block, still needs to avoid leaking a raw stack trace to a visitor in production. ASP.NET Core's own exception-handling middleware, configured once in `Program.cs`, closes that gap for the whole application:

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
}
else
{
    app.UseDeveloperExceptionPage();
}

app.UseRouting();
app.MapRazorPages();
app.Run();
In development, `UseDeveloperExceptionPage` shows the full stack trace and query details, genuinely useful while debugging locally. In production, `UseExceptionHandler("/Error")` catches anything unhandled and redirects to a generic error page instead, where `HttpContext.Features.Get<IExceptionHandlerPathFeature>()` can log the original failing route and exception server-side before showing the visitor nothing more alarming than an apology and a reference number. This is the layer that catches whatever the page-level `try`/`catch` above didn't, not a replacement for it.

Testing the Failure Path, Not Just the Success Path

This course's habit of confirming a query directly in Azure Data Studio before wiring it into a `SqlCommand` applies here too, with one addition: it's worth deliberately running the failure case as well as the success case. Running `EXEC dbo.usp_UpdateCustomerEmail @CustomerID = 99999, @NewEmail = 'test@example.com'` against a `CustomerID` that doesn't exist, directly in Azure Data Studio, confirms the custom `THROW 50001` actually fires as expected, before the C# code around it is trusted to catch and translate it correctly.

Frequently Asked Questions

Why catch `SqlException` separately from a general `Exception`, instead of one broad `catch` block for everything? A `SqlException` carries a `Number`, a `Procedure`, and a `LineNumber`, specific details worth inspecting and worth logging separately from an unrelated failure like a null reference or a missing configuration value. Catching the specific type first, then the general type as a fallback, lets the code respond appropriately to each kind of failure rather than treating every error the same way.

What happens if an error's `Number` doesn't match any of the cases in the `switch` statement? It falls into the `default` case, a safe, generic message, the same outcome a legacy `ErrorHandler` sub would have reached by simply printing whatever `Err.number` happened to be. Nothing crashes just because an error wasn't specifically anticipated.

Should the raw `SqlException.Message` ever be shown directly to a visitor? No, for the same reason raw error text was avoided in the view section above: SQL Server's own exception messages can mention table or column names that have no business being visible outside the application. Log the full exception server-side, exactly as this lesson's `_logger.LogError` call would, and show the visitor only a message chosen deliberately for that purpose.

Why `SET XACT_ABORT ON` specifically, rather than relying on the `CATCH` block's own `ROLLBACK`? `XACT_ABORT ON` ensures that if any statement inside the transaction fails, the entire batch stops and the transaction becomes uncommittable immediately, which is why the `CATCH` block checks `XACT_STATE()` before rolling back at all. Without it, certain errors could leave the transaction in a state where continuing to execute further statements, rather than aborting, becomes possible, which is rarely what a multi-statement update actually wants.

Does this lesson's error handling apply the same way to a simple `SELECT`, not just an `UPDATE`? The `SqlException`-then-`Exception` pattern in the `PageModel` applies equally to any database call, a `SELECT` through `ExecuteReaderAsync` can fail for the same reasons, a lost connection, a timeout, a permissions problem. The `TRY...CATCH`/`XACT_ABORT` pattern inside SQL Server itself matters most for multi-statement transactions like this lesson's `UPDATE`; a single read-only `SELECT` has nothing to roll back in the first place.

What's the difference between a `-2` command timeout and a `1205` deadlock? A `-2` means the client gave up waiting after `CommandTimeout` seconds elapsed, the request may still be running on the server; a `1205` means SQL Server itself detected a deadlock between two or more transactions and deliberately killed one of them, this one, to let the others proceed. Both are worth telling the visitor to simply try again, but they originate from different places, one from the client's patience running out, one from SQL Server's own deadlock detection.

Could the error-number `switch` statement grow to cover many more SQL Server error numbers over time? Yes, and that's exactly how it should grow, incrementally, as specific errors worth a tailored message are actually encountered. There's no need to anticipate every possible SQL Server error number in advance; the `default` case already covers everything not yet worth a specific response.

Does any of this change if the query runs through inline SQL text instead of a stored procedure? No. `CommandType.Text` and `CommandType.StoredProcedure` both raise the same `SqlException` type, with the same `Errors` collection, when something goes wrong; the `PageModel`'s `catch` block doesn't need to know or care which way the underlying `SqlCommand` was built.

Why log the full exception server-side at all, if the visitor only ever sees a generic message? Because the generic message is the whole point, visitors shouldn't see SQL Server's own error text, but someone still has to be able to find out what actually happened. A logged `SqlException` with its number, procedure name, and line number gives a developer everything needed to track down a recurring problem later, even though none of that detail ever reaches the page itself.

Does `SqlException.Errors` ever contain more than one error at once? Yes. A single failed batch can raise more than one error, a severe one alongside one or more informational ones, which is exactly why this lesson's code loops over the whole `Errors` collection with `foreach` rather than only inspecting `sqlEx.Number`, the first error's number alone.

What's Ahead

This lesson closes out Module 4's content with the one piece every earlier lesson quietly assumed away: what a Razor Page does when a database call doesn't succeed, at the SQL Server level, the `PageModel` level, and as a last-resort safety net across the whole application. The next lesson wraps up this module with a conclusion and a quiz covering what's been built since Lesson 1.

SEMrush Software 9 SEMrush Banner 9