Serenity Operating System
at master 115 lines 3.7 kB view raw
1/* 2 * Copyright (c) 2022, Matthew Olsson <mattco@serenityos.org> 3 * 4 * SPDX-License-Identifier: BSD-2-Clause 5 */ 6 7#pragma once 8 9#include <AK/DeprecatedString.h> 10#include <AK/String.h> 11#include <AK/Vector.h> 12 13namespace PDF { 14 15class Error { 16public: 17 enum class Type { 18 Parse, 19 Internal, 20 MalformedPDF, 21 RenderingUnsupported 22 }; 23 24 Error(AK::Error error) 25 : m_type(Type::Internal) 26 , m_message(DeprecatedString::formatted("Internal error while processing PDF file: {}", error.string_literal())) 27 { 28 } 29 30 Error(Type type, DeprecatedString const& message) 31 : Error(type, String::from_deprecated_string(message).release_value_but_fixme_should_propagate_errors()) 32 { 33 } 34 35 Error(Type type, String const& message) 36 : m_type(type) 37 { 38 switch (type) { 39 case Type::Parse: 40 m_message = DeprecatedString::formatted("Failed to parse PDF file: {}", message); 41 break; 42 case Type::Internal: 43 m_message = DeprecatedString::formatted("Internal error while processing PDF file: {}", message); 44 break; 45 case Type::MalformedPDF: 46 m_message = DeprecatedString::formatted("Malformed PDF file: {}", message); 47 break; 48 case Type::RenderingUnsupported: 49 m_message = DeprecatedString::formatted("Rendering of feature not supported: {}", message); 50 break; 51 } 52 } 53 54 Type type() const { return m_type; } 55 DeprecatedString const& message() const { return m_message; } 56 57#define DEFINE_STATIC_ERROR_FUNCTIONS(name, type) \ 58 static Error name##_error(StringView message) \ 59 { \ 60 return maybe_with_string(Type::type, String::from_utf8(message)); \ 61 } \ 62 \ 63 template<typename... Parameters> \ 64 static Error name##_error(CheckedFormatString<Parameters...>&& fmtstr, Parameters const&... parameters) \ 65 { \ 66 return maybe_with_string(Type::type, String::formatted(move(fmtstr), parameters...)); \ 67 } 68 69 DEFINE_STATIC_ERROR_FUNCTIONS(parse, Parse) 70 DEFINE_STATIC_ERROR_FUNCTIONS(internal, Internal) 71 DEFINE_STATIC_ERROR_FUNCTIONS(malformed, MalformedPDF) 72 DEFINE_STATIC_ERROR_FUNCTIONS(rendering_unsupported, RenderingUnsupported) 73 74private: 75 Type m_type; 76 DeprecatedString m_message; 77 78 static Error maybe_with_string(Type type, ErrorOr<String> maybe_string) 79 { 80 if (maybe_string.is_error()) 81 return Error { type, String {} }; 82 return Error { type, maybe_string.release_value() }; 83 } 84}; 85 86class Errors { 87 88public: 89 Errors() = default; 90 Errors(Error&& error) 91 { 92 m_errors.empend(move(error)); 93 } 94 95 Vector<Error> const& errors() const 96 { 97 return m_errors; 98 } 99 100 void add_error(Error&& error) 101 { 102 m_errors.empend(move(error)); 103 } 104 105private: 106 Vector<Error> m_errors; 107}; 108 109template<typename T> 110using PDFErrorOr = ErrorOr<T, Error>; 111 112template<typename T> 113using PDFErrorsOr = ErrorOr<T, Errors>; 114 115}