How do I handle Supabase Postgrest Exception in ASP.NET Core (controller-based web API)?
I'm testing an endpoint (using Swagger) that gets a table row using non-existant (uuid) id.
This is the first line of response body I get (Internal Server Error):
Supabase.Postgrest.Exceptions.PostgrestException: {"code":"22P02","details":null,"hint":null,"message":"invalid input syntax for type uuid: \"non-existant-uuid\""}
Program.cs:
using Project.Services;
using Supabase;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddControllers().AddNewtonsoftJson();
var url = "url" ?? "Unknown URL";
var key = "key";
var options = new SupabaseOptions
{
AutoRefreshToken = true,
AutoConnectRealtime = true,
};
builder.Services.AddSingleton(provider => new Supabase.Client(url, key, options));
builder.Services.AddSingleton<DatabasesService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
Model file (Databases.cs):
using Supabase.Postgrest.Models;
using Supabase.Postgrest.Attributes;
namespace Project.Models;
[Table("databases")]
public class Database : BaseModel
{
[PrimaryKey("id", false)] // uuid
public string? Id { get; set; }
[Column("name")] // varchar
public string? Name { get; set; }
}
Service file (DatabasesService.cs):
using Project.Models;
using Supabase;
namespace Project.Services;
public class DatabasesService
{
private readonly Client _supabaseClient;
public DatabasesService(Client supabaseClient)
{
_supabaseClient = supabaseClient;
}
public async Task<List<Database>> GetAll()
{
var result = await _supabaseClient
.From<Database>().Get();
return result.Models;
}
public async Task<List<Database>> GetById(string id)
{
var result = await _supabaseClient
.From<Database>()
.Where(x => x.Id == id)
.Get();
return result.Models;
}
}
Controller file (DatabasesController.cs):
using Project.Services;
using Project.Models;
using Microsoft.AspNetCore.Mvc;
namespace Project.Controllers;
[ApiController]
[Route("[controller]")]
public class DatabasesController : ControllerBase
{
DatabasesService _databasesService;
public DatabasesController(DatabasesService databasesService) =>
_databasesService = databasesService;
[HttpGet]
public async Task<List<Database>> GetAll() =>
await _databasesService.GetAll();
[HttpGet("{id}")]
public async Task<ActionResult<Database>> GetById(string id)
{
var response = await _databasesService.GetById(id);
var database = response.FirstOrDefault();
if (database is not null)
return database;
else
return NotFound();
}
}
I mananged to handle the exception by adding try - catch block (catching PostgrestException
) in controller file.