sqlight
sqlight copied to clipboard
Better error message when using connection from wrong process or after closing (Erlang)
Hello hello!
I accidentally introduced a bug in my application where I was passing a connection to another erlang actor and it kept crashing. Took me a while to figure out that I was passing the connection from with_connection after the scope was already gone. Obviously on me, but I was wondering if we can provide a better error message for this. Same for when you close the connection and use it afterwards.
I am not super familiar with the details of the erlang implementation, so maybe this is not even possible. Happy to make a PR though if this is deemed viable.
Example Code:
import app/env
import gleam/dynamic/decode
import gleam/erlang/process
import sqlight
pub fn foo(conn: sqlight.Connection) {
echo sqlight.query(
"select 1",
on: conn,
with: [],
expecting: decode.success(1),
)
}
pub fn bar() {
let env = env.get_env()
use conn <- sqlight.with_connection(env.db_path)
process.spawn(fn() { foo(conn) })
}
pub fn main() {
let _ = bar()
process.sleep_forever()
}
Output:
gleam dev
Compiling app
Compiled in 0.41s
Running app_dev.main
=CRASH REPORT==== 29-Oct-2025::12:07:16.917653 ===
crasher:
initial call: app_dev:'-bar/0-anonymous-0-'/0
pid: <0.115.0>
registered_name: []
exception error: bad argument
in function esqlite3_nif:error_info/1
called as esqlite3_nif:error_info(#Ref<0.302291343.3268280346.105147>)
in call from sqlight_ffi:to_error/2 (/app/build/dev/erlang/sqlight/_gleam_artefacts/sqlight_ffi.erl:61)
in call from sqlight:query/4 (src/sqlight.gleam:387)
in call from app_dev:foo/1 (dev/app_dev.gleam:11)
ancestors: [<0.82.0>]
message_queue_len: 0
messages: []
links: [<0.82.0>]
dictionary: []
trap_exit: false
status: running
heap_size: 233
stack_size: 29
reductions: 100
neighbours:
neighbour:
pid: <0.82.0>
registered_name: []
initial_call: {erlang,apply,2}
current_function: {code_server,call,1}
ancestors: []
message_queue_len: 0
links: [<0.10.0>,<0.115.0>]
trap_exit: false
status: waiting
heap_size: 233
stack_size: 16
reductions: 3909
current_stacktrace: [{code_server,call,1,[{file,"code_server.erl"},{line,163}]},
{code,ensure_loaded,1,[{file,"code.erl"},{line,578}]},
{error_handler,undefined_function,3,
[{file,"error_handler.erl"},{line,86}]},
{gleam_erlang_ffi,sleep_forever,0,
[{file,
"/app/build/dev/erlang/gleam_erlang/_gleam_artefacts/gleam_erlang_ffi.erl"},
{line,27}]},
{app@@main,run_module,1,
[{file,
"/app/build/dev/erlang/app/_gleam_artefacts/app@@main.erl"},
{line,24}]}]
runtime error: Erlang exit
An error occurred outside of Gleam.
erlang:exit(Badarg)
stacktrace:
esqlite3_nif.error_info unknown source
sqlight_ffi.to_error /app/build/dev/erlang/sqlight/_gleam_artefacts/sqlight_ffi.erl:61
sqlight.query src/sqlight.gleam:387
app_dev.foo dev/app_dev.gleam:11
proc_lib.init_p proc_lib.erl:317