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
|
||||
|
||||
def []?(key : K) : V?
|
||||
begin
|
||||
read file_path key
|
||||
rescue
|
||||
# FIXME: Only rescue JSON and “no such file” errors.
|
||||
return nil
|
||||
end
|
||||
self[key]
|
||||
rescue MissingEntry
|
||||
# FIXME: Only rescue JSON and “no such file” errors.
|
||||
return nil
|
||||
end
|
||||
|
||||
def [](key : K) : V
|
||||
raise MissingEntry.new(key) unless ::File.exists? file_path key
|
||||
|
||||
read file_path key
|
||||
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 "json"
|
||||
|
||||
require "./exceptions.cr"
|
||||
require "./indexer.cr"
|
||||
|
||||
class FSDB::Index(V) < FSDB::Indexer(V)
|
||||
|
@ -51,8 +52,18 @@ class FSDB::Index(V) < FSDB::Indexer(V)
|
|||
::File.delete symlink
|
||||
end
|
||||
|
||||
def get(index : String) : V?
|
||||
V.from_json ::File.read "#{file_path_index index}"
|
||||
def get(index : String) : V
|
||||
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
|
||||
|
||||
private def dir_path_indices
|
||||
|
@ -68,6 +79,3 @@ class FSDB::Index(V) < FSDB::Indexer(V)
|
|||
end
|
||||
end
|
||||
|
||||
class FSDB::IndexOverload < Exception
|
||||
end
|
||||
|
||||
|
|
Loading…
Reference in New Issue