Custom exceptions for common errors.

remotes/1702071717368387340/master
Luka Vandervelden 2019-12-11 22:08:26 +01:00
parent 8ba15394b7
commit 675cb1cdd8
3 changed files with 36 additions and 11 deletions

View File

@ -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

17
src/fsdb/exceptions.cr Normal file
View File

@ -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

View File

@ -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