Error API Reference¶
Overview¶
The Error
class represents an error that occurred during an operation. It contains information about the error, including a code, message, and optional metadata.
Properties¶
Code¶
public ErrorCode Code { get; }
Message¶
public string Message { get; }
Metadata¶
public IReadOnlyDictionary<string, object> Metadata { get; }
Static Factory Methods¶
Create¶
public static Error Create(string message)
public static Error Create(ErrorCode code, string message)
public static Error Create(ErrorCode code, string message, Dictionary<string, object> metadata)
FromException¶
public static Error FromException(Exception exception)
public static Error FromException(Exception exception, ErrorCode code)
public static Error FromException(Exception exception, ErrorCode code, Dictionary<string, object> metadata)
Instance Methods¶
WithMetadata¶
public Error WithMetadata(string key, object value)
public Error WithMetadata(Dictionary<string, object> metadata)
ToString¶
public override string ToString()
Examples¶
Creating Errors¶
// Simple error
var error = Error.Create("Operation failed");
// Coded error
var notFoundError = Error.Create(ErrorCode.NotFound, "Resource not found");
// Error with metadata
var validationError = Error.Create(
ErrorCode.ValidationError,
"Invalid input",
new Dictionary<string, object> { { "Field", "Name" } }
);
// Error from exception
try
{
// Some operation that might throw
}
catch (Exception ex)
{
var error = Error.FromException(ex, ErrorCode.InternalError);
}
Working with Errors¶
// Adding metadata
var detailedError = error.WithMetadata("Timestamp", DateTime.UtcNow);
// Combining metadata
var combinedError = error.WithMetadata(new Dictionary<string, object>
{
{ "UserId", 123 },
{ "Action", "Update" }
});
// String representation
Console.WriteLine(error.ToString());
// Output: Error[NotFound]: Resource not found