LoaderError.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2021, kleines Filmröllchen <filmroellchen@serenityos.org>.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Error.h>
  8. #include <AK/FlyString.h>
  9. #include <errno.h>
  10. namespace Audio {
  11. struct LoaderError {
  12. enum class Category : u32 {
  13. // The error category is unknown.
  14. Unknown = 0,
  15. IO,
  16. // The read file doesn't follow the file format.
  17. Format,
  18. // Equivalent to an ASSERT(), except non-crashing.
  19. Internal,
  20. // The loader encountered something in the format that is not yet implemented.
  21. Unimplemented,
  22. };
  23. Category category { Category::Unknown };
  24. // Binary index: where in the file the error occurred.
  25. size_t index { 0 };
  26. FlyString description { String::empty() };
  27. constexpr LoaderError() = default;
  28. LoaderError(Category category, size_t index, FlyString description)
  29. : category(category)
  30. , index(index)
  31. , description(move(description))
  32. {
  33. }
  34. LoaderError(FlyString description)
  35. : description(move(description))
  36. {
  37. }
  38. LoaderError(Category category, FlyString description)
  39. : category(category)
  40. , description(move(description))
  41. {
  42. }
  43. LoaderError(LoaderError&) = default;
  44. LoaderError(LoaderError&&) = default;
  45. LoaderError(Error&& error)
  46. {
  47. if (error.is_errno()) {
  48. auto code = error.code();
  49. description = String::formatted("{} ({})", strerror(code), code);
  50. if (code == EBADF || code == EBUSY || code == EEXIST || code == EIO || code == EISDIR || code == ENOENT || code == ENOMEM || code == EPIPE)
  51. category = Category::IO;
  52. } else {
  53. description = error.string_literal();
  54. }
  55. }
  56. };
  57. }
  58. // Convenience TRY-like macro to convert an Error to a LoaderError
  59. #define LOADER_TRY(expression) \
  60. ({ \
  61. auto _temporary_result = (expression); \
  62. if (_temporary_result.is_error()) \
  63. return LoaderError(_temporary_result.release_error()); \
  64. _temporary_result.release_value(); \
  65. })