The TaskHub.Shared.Response module provides a standardized way to return results from services, handlers, and APIs. It emphasizes clarity, type safety, and built-in telemetry.
The design is based on the Result Pattern, which avoids using exceptions for expected control flow (like validation errors or “not found” scenarios).
ResultCode and a Message.Result or ValueResult<T>.public class Result
{
public bool IsSuccess => ResultCode == 0;
public int ResultCode { get; init; }
public string Message { get; init; }
// Implicit conversion from OpResult
public static implicit operator Result(OpResult op) => new(op.ResultCode, op.Message);
}
public sealed class ValueResult<T> : Result
{
public T? Data { get; init; }
// Implicit conversion from OpResult
public static implicit operator ValueResult<T>(OpResult op) => new(op.ResultCode, op.Message, default);
}
OpResult is a helper that simplifies the syntax for returning results from methods.
public class OpResult(int code, string message)
{
public bool IsSuccess => ResultCode == 0;
public int ResultCode { get; init; } = code;
public string Message { get; init; } = message;
public TResult As<TResult>() where TResult : Result => (TResult)(Result)this;
}
Because Result and ValueResult<T> define implicit operators for OpResult, you can return an OpResult from a method that expects a Result:
public Result DoWork()
{
if (failure) return new OpResult(1, "Failed");
return new OpResult(0, "Success");
}
Every time a Result or ValueResult<T> is instantiated, it automatically interacts with the current OpenTelemetry Activity.
result.code: The integer code of the result.result.message: The message associated with the result.result.isSuccess: A boolean indicating success.If IsSuccess is true, the activity status is set to Ok. Otherwise, it is set to Error.