From 675cb1cdd8e9b6db4d313ef456784e8672e555ad Mon Sep 17 00:00:00 2001 From: Luka Vandervelden Date: Wed, 11 Dec 2019 22:08:26 +0100 Subject: [PATCH] Custom exceptions for common errors. --- src/fsdb.cr | 12 ++++++------ src/fsdb/exceptions.cr | 17 +++++++++++++++++ src/fsdb/index.cr | 18 +++++++++++++----- 3 files changed, 36 insertions(+), 11 deletions(-) create mode 100644 src/fsdb/exceptions.cr diff --git a/src/fsdb.cr b/src/fsdb.cr index 098881d..b1256ee 100644 --- a/src/fsdb.cr +++ b/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 diff --git a/src/fsdb/exceptions.cr b/src/fsdb/exceptions.cr new file mode 100644 index 0000000..ea89972 --- /dev/null +++ b/src/fsdb/exceptions.cr @@ -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 + diff --git a/src/fsdb/index.cr b/src/fsdb/index.cr index e02ffcb..a67d6b3 100644 --- a/src/fsdb/index.cr +++ b/src/fsdb/index.cr @@ -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 -