Custom exceptions for common errors.
parent
8ba15394b7
commit
675cb1cdd8
12
src/fsdb.cr
12
src/fsdb.cr
|
@ -52,15 +52,15 @@ class FSDB::DataBase(K, V)
|
||||||
end
|
end
|
||||||
|
|
||||||
def []?(key : K) : V?
|
def []?(key : K) : V?
|
||||||
begin
|
self[key]
|
||||||
read file_path key
|
rescue MissingEntry
|
||||||
rescue
|
# FIXME: Only rescue JSON and “no such file” errors.
|
||||||
# FIXME: Only rescue JSON and “no such file” errors.
|
return nil
|
||||||
return nil
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
def [](key : K) : V
|
def [](key : K) : V
|
||||||
|
raise MissingEntry.new(key) unless ::File.exists? file_path key
|
||||||
|
|
||||||
read file_path key
|
read file_path key
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,17 @@
|
||||||
|
|
||||||
|
class FSDB::MissingEntry < Exception
|
||||||
|
getter index : String?
|
||||||
|
getter key : String
|
||||||
|
|
||||||
|
def initialize(@index, @key)
|
||||||
|
super "no entry in index '#{@index}' for key '#{@key}''"
|
||||||
|
end
|
||||||
|
|
||||||
|
def initialize(@key)
|
||||||
|
super "no entry for key '#{@key}' in database"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
class FSDB::IndexOverload < Exception
|
||||||
|
end
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
require "file_utils"
|
require "file_utils"
|
||||||
require "json"
|
require "json"
|
||||||
|
|
||||||
|
require "./exceptions.cr"
|
||||||
require "./indexer.cr"
|
require "./indexer.cr"
|
||||||
|
|
||||||
class FSDB::Index(V) < FSDB::Indexer(V)
|
class FSDB::Index(V) < FSDB::Indexer(V)
|
||||||
|
@ -51,8 +52,18 @@ class FSDB::Index(V) < FSDB::Indexer(V)
|
||||||
::File.delete symlink
|
::File.delete symlink
|
||||||
end
|
end
|
||||||
|
|
||||||
def get(index : String) : V?
|
def get(index : String) : V
|
||||||
V.from_json ::File.read "#{file_path_index index}"
|
file_path = file_path_index index
|
||||||
|
|
||||||
|
raise MissingEntry.new(@name, index) unless ::File.exists? file_path
|
||||||
|
|
||||||
|
V.from_json ::File.read file_path
|
||||||
|
end
|
||||||
|
|
||||||
|
def get?(index : String) : V?
|
||||||
|
get index
|
||||||
|
rescue MissingEntry
|
||||||
|
nil
|
||||||
end
|
end
|
||||||
|
|
||||||
private def dir_path_indices
|
private def dir_path_indices
|
||||||
|
@ -68,6 +79,3 @@ class FSDB::Index(V) < FSDB::Indexer(V)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
class FSDB::IndexOverload < Exception
|
|
||||||
end
|
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue