MySQL · Execute

Business errors raised by a procedure

Business rules the database enforces, in three scenarios. sp_reserve_credit refuses an account on hold (SIGNAL SQLSTATE '45000' … MYSQL_ERRNO = 50101) and an amount over the credit limit (MYSQL_ERRNO = 50102). Both arrive as ARX3005 RaisedByDatabase with the procedure's message and its error number as NativeCode, so the application can tell "the database said no" from "something broke", and branch on the procedure's own number.

Set up for this page

The scenarios build on the sample application: SampleContext.cs (the dbContext every sample is given); SampleOutput.cs (Step and Show, which print); SampleContext.Application.cs (dbContext.Service, the application's ARX service); SampleCatalog.cs (the tables' ids, keys, lookups and display names).

Before scenario 1 the sample runs this, so the service and the rows the scenarios use are there:

Set up
var open = new ArxEntity("account");
open["name"] = "Credit Cove";
open["account_number"] = "ACC-E801";
open["credit_limit"] = 100m;
var openId = await service.CreateAsync(open);
var held = new ArxEntity("account");
held["name"] = "Held Harbour";
held["account_number"] = "ACC-E802";
held["credit_limit"] = 500m;
held["status"] = new ArxSelectionSetValue("AccountStatus", "ON_HOLD");
var heldId = await service.CreateAsync(held);

1 Within the limit

40 of a limit of 100: reserved.

Already in scope: service (ArxMySqlDbService), accountId (ArxRecordId)

C#
await service.ExecuteAsync(Reserve(accountId, 40m));
Console.WriteLine("40.00 reserved");
Used above

Defined once in this sample.

private static ArxProcedureExpression Reserve(ArxRecordId accountId, decimal amount)
{
    var procedure = new ArxProcedureExpression("sp_reserve_credit");
    procedure.AddParameter("p_account_id", accountId.AsInt64());
    procedure.AddParameter("p_amount", amount);
    return procedure;
}

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT credit_limit
FROM account
WHERE account_number = 'ACC-E801';

Expect: 60.00.

2 Over the limit

250 more: refused, with the procedure's message and number; nothing changed.

Already in scope: service (ArxMySqlDbService), accountId (ArxRecordId)

C#
try
{
    await service.ExecuteAsync(Reserve(accountId, 250m));
}
catch (ArxDatabaseException error) when (error.Code == ArxErrorCode.RaisedByDatabase)
{
    Console.WriteLine(error.Message);
    Console.WriteLine($"number {error.NativeCode}; for the user: \"{ForTheUser(error)}\"");
}
Used above

Defined once in this sample.

private static ArxProcedureExpression Reserve(ArxRecordId accountId, decimal amount)
{
    var procedure = new ArxProcedureExpression("sp_reserve_credit");
    procedure.AddParameter("p_account_id", accountId.AsInt64());
    procedure.AddParameter("p_amount", amount);
    return procedure;
}

private static string ForTheUser(ArxException error) => error.NativeCode switch
{
    "50101" => "This account is on hold. Please contact accounts.",
    "50102" => "That's over the credit limit.",
    _ => "The request couldn't be completed."
};

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT credit_limit
FROM account
WHERE account_number = 'ACC-E801';

Expect: 60.00: the refused call changed nothing.

3 An account on hold: the procedure's own number

An account on hold: the procedure's own number, 50101, so the application shows another message.

Already in scope: service (ArxMySqlDbService), accountId (ArxRecordId)

C#
try
{
    await service.ExecuteAsync(Reserve(accountId, 10m));
}
catch (ArxDatabaseException error) when (error.Code == ArxErrorCode.RaisedByDatabase)
{
    Console.WriteLine($"{error.NativeCode}: {error.Message}; for the user: \"{ForTheUser(error)}\"");
}
Used above

Defined once in this sample.

private static ArxProcedureExpression Reserve(ArxRecordId accountId, decimal amount)
{
    var procedure = new ArxProcedureExpression("sp_reserve_credit");
    procedure.AddParameter("p_account_id", accountId.AsInt64());
    procedure.AddParameter("p_amount", amount);
    return procedure;
}

private static string ForTheUser(ArxException error) => error.NativeCode switch
{
    "50101" => "This account is on hold. Please contact accounts.",
    "50102" => "That's over the credit limit.",
    _ => "The request couldn't be completed."
};

Check it in the database

SQL

Run it in any SQL tool connected to the database, after the code has run.

SELECT status, credit_limit
FROM account
WHERE account_number = 'ACC-E802';

Expect: ON_HOLD, 500.00.

Run the complete sample

The code above comes from one program, built in a fresh project and run against the database. To run it yourself, here is every file and step.

The program, its files and how to run it

Run it locally

  1. .NET SDK: .NET SDK 10.0.100 or later 10.0.x (target net10.0).
  2. Create the project:
    Terminal
    dotnet new console -n ArxSample -f net10.0
    cd ArxSample
  3. Install the packages:
    Terminal
    dotnet add package ARX.SDK.MySQL --version 1.0.0-rc.1
  4. Database: a MySQL 8.4 (tested with 8.4.13) database with the sample schema.
  5. Configuration: set ARX_SAMPLES_MYSQL to its connection string. Nothing is hard-coded.
  6. Source code: add the files of the sample application this sample uses (SampleContext.cs, SampleOutput.cs, SampleContext.Application.cs, SampleCatalog.cs), then replace Program.cs and add the other file below, with the file names shown.
  7. Run it:
    Terminal
    dotnet run
  8. Expected output: below.

The files

Program.cs

Runs the sample. Generated for this page; it reads the connection string from the environment.

using ArxSamples.MySQL;
using ArxSamples.MySQL.Operations.Execute.RealCases;

// The connection string comes from the environment, never from the code (see "Configure the connection").
var connectionString = Environment.GetEnvironmentVariable("ARX_SAMPLES_MYSQL")
    ?? throw new InvalidOperationException("Set the ARX_SAMPLES_MYSQL environment variable to your MySQL connection string.");

await new RealCase4_BusinessErrorsFromTheDatabase().RunAsync(new SampleContext(connectionString));
RealCase4_BusinessErrorsFromTheDatabase.cs

The sample, as it is in the repository.

using ARX.SDK;
using ARX.SDK.Query;
using ARX.SDK.Services;
using static ArxSamples.MySQL.SampleOutput;

namespace ArxSamples.MySQL.Operations.Execute.RealCases;

/// <summary>
/// Business rules the database enforces, in three scenarios. <c>sp_reserve_credit</c> refuses an account on hold
/// (<c>SIGNAL SQLSTATE '45000' … MYSQL_ERRNO = 50101</c>) and an amount over the credit limit (<c>MYSQL_ERRNO = 50102</c>).
/// Both arrive as
/// <c>ARX3005 RaisedByDatabase</c> with the procedure's message and its error number as <c>NativeCode</c>, so the
/// application can tell "the database said no" from "something broke", and branch on the procedure's own number.
/// </summary>
public sealed class RealCase4_BusinessErrorsFromTheDatabase : ISample
{
    public string Name => "execute-real-4-business-errors-from-the-database";

    public string Title => "Business errors raised by a procedure";

    public async Task RunAsync(SampleContext dbContext)
    {
        var open = new ArxEntity("account");
        open["name"] = "Credit Cove";
        open["account_number"] = "ACC-E801";
        open["credit_limit"] = 100m;
        var openId = await dbContext.Service.CreateAsync(open);

        var held = new ArxEntity("account");
        held["name"] = "Held Harbour";
        held["account_number"] = "ACC-E802";
        held["credit_limit"] = 500m;
        held["status"] = new ArxSelectionSetValue("AccountStatus", "ON_HOLD");
        var heldId = await dbContext.Service.CreateAsync(held);

        await Scenario1_WithinTheLimitAsync(dbContext, openId);

        await Scenario2_OverTheLimitAsync(dbContext, openId);

        await Scenario3_OnHoldAsync(dbContext, heldId);
    }

    private static ArxProcedureExpression Reserve(ArxRecordId accountId, decimal amount)
    {
        var procedure = new ArxProcedureExpression("sp_reserve_credit");
        procedure.AddParameter("p_account_id", accountId.AsInt64());
        procedure.AddParameter("p_amount", amount);
        return procedure;
    }

    /// <summary>The message for the user, by the procedure's own error number.</summary>
    private static string ForTheUser(ArxException error) => error.NativeCode switch
    {
        "50101" => "This account is on hold. Please contact accounts.",
        "50102" => "That's over the credit limit.",
        _ => "The request couldn't be completed."
    };

    /// <summary>1. 40 of a limit of 100: reserved.</summary>
    private static async Task Scenario1_WithinTheLimitAsync(SampleContext dbContext, ArxRecordId accountId)
    {
        Step("1. Within the limit");

        await dbContext.Service.ExecuteAsync(Reserve(accountId, 40m));
        Show("40.00 reserved");

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT credit_limit
         * FROM account
         * WHERE account_number = 'ACC-E801';
         * -- Expect: 60.00.
         * ===========================================================
         */
    }

    /// <summary>2. 250 more: refused, with the procedure's message and number; nothing changed.</summary>
    private static async Task Scenario2_OverTheLimitAsync(SampleContext dbContext, ArxRecordId accountId)
    {
        Step("2. Over the limit");

        try
        {
            await dbContext.Service.ExecuteAsync(Reserve(accountId, 250m));
        }
        catch (ArxDatabaseException error) when (error.Code == ArxErrorCode.RaisedByDatabase)
        {
            ShowError(error);
            Show($"number {error.NativeCode}; for the user: \"{ForTheUser(error)}\"");
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT credit_limit
         * FROM account
         * WHERE account_number = 'ACC-E801';
         * -- Expect: 60.00: the refused call changed nothing.
         * ===========================================================
         */
    }

    /// <summary>3. An account on hold: the procedure's own number, <c>50101</c>, so the application shows another message.</summary>
    private static async Task Scenario3_OnHoldAsync(SampleContext dbContext, ArxRecordId accountId)
    {
        Step("3. An account on hold: the procedure's own number");

        try
        {
            await dbContext.Service.ExecuteAsync(Reserve(accountId, 10m));
        }
        catch (ArxDatabaseException error) when (error.Code == ArxErrorCode.RaisedByDatabase)
        {
            Show($"{error.NativeCode}: {error.Message}; for the user: \"{ForTheUser(error)}\"");
        }

        /* ===========================================================
         * [DIRECT QUERY CHECK]
         * -----------------------------------------------------------
         * SELECT status, credit_limit
         * FROM account
         * WHERE account_number = 'ACC-E802';
         * -- Expect: ON_HOLD, 500.00.
         * ===========================================================
         */
    }
}

Expected output

What dotnet run printed when the sample was verified, on a freshly created sample schema. Ids differ when the tables already hold rows.

Output
  > 1. Within the limit
      40.00 reserved
  > 2. Over the limit
      caught ArxDatabaseException: ARX3005 RaisedByDatabase: credit limit exceeded: limit 60.00, asked 250.00; reserve 60.00 or less.
      number 50102; for the user: "That's over the credit limit."
  > 3. An account on hold: the procedure's own number
      50101: ARX3005 RaisedByDatabase: account 2 is on hold: release the hold first.; for the user: "This account is on hold. Please contact accounts."