{"id":15284293,"url":"https://github.com/deshansl/returns","last_synced_at":"2025-10-11T14:31:49.614Z","repository":{"id":245552064,"uuid":"817062857","full_name":"DeshanSL/returns","owner":"DeshanSL","description":"Simplify error handling and improve code readability with the Result Pattern","archived":false,"fork":false,"pushed_at":"2024-10-02T02:31:28.000Z","size":56,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-09-30T01:51:29.504Z","etag":null,"topics":["csharp","dotnet","dotnet-core","dotnetnugetutil","nuget","nuget-package","result","result-pattern","resultpattern","return","returns","simple"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DeshanSL.png","metadata":{"files":{"readme":"Readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-06-19T00:21:59.000Z","updated_at":"2024-11-01T06:06:02.000Z","dependencies_parsed_at":"2024-08-03T03:10:07.282Z","dependency_job_id":"5f595105-237f-43e3-b407-130910a6abcd","html_url":"https://github.com/DeshanSL/returns","commit_stats":null,"previous_names":["deshansl/returns"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/DeshanSL/returns","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DeshanSL%2Freturns","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DeshanSL%2Freturns/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DeshanSL%2Freturns/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DeshanSL%2Freturns/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DeshanSL","download_url":"https://codeload.github.com/DeshanSL/returns/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DeshanSL%2Freturns/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279007457,"owners_count":26084313,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-11T02:00:06.511Z","response_time":55,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csharp","dotnet","dotnet-core","dotnetnugetutil","nuget","nuget-package","result","result-pattern","resultpattern","return","returns","simple"],"created_at":"2024-09-30T14:52:58.899Z","updated_at":"2025-10-11T14:31:49.309Z","avatar_url":"https://github.com/DeshanSL.png","language":"C#","readme":"### Simplify error handling and improve code readability with the Result Pattern\n\n## Get Started\n\n#### Install nuget package using .Net CLI\n\nor nuget using Nuget package manager GUI by searching DeepCode.Return\n\n```bash\ndotnet add package DeepCode.Return --version 1.0.1\n```\n\n## How To Use\n\n#### Define method return type with Return struct with TResult type parameter\n\nTResult is type of the return\n\n```csharp\nnamespace Invoicing.Application.Orders.Commands.CreateOrderCommand;\n\ninternal class CreateOrderCommandHandler : IRequestHandler\u003cCreateOrderCommand, Return\u003cOrder\u003e\u003e\n{\n    public async Task\u003cReturn\u003cOrder\u003e\u003e Handle(CreateOrderCommand request, CancellationToken cancellationToken)\n    {\n        Order order;\n        //order creation logic\n        return order;\n    }\n}\n```\n\nfor non async methods\n\n```csharp\npublic Return\u003cOrder\u003e CreateOrder(CreateOrder request, CancellationToken cancellationToken)\n{\n    Order order;\n\n    //order creation logic\n    return order;\n}\n```\n\n#### Return struct can be used when there's no return value but to notify if function was success or not\n\n```csharp\npublic Return SendEmail()\n{\n    return Return.Success();\n}\n```\n\n### How to extract if state is success\n\n```csharp\n\nReturn\u003cOrder\u003e orderCreateResult = CreateOrder(request, cancellationToken);\nif(orderCreateResult.IsFailure)\n{\n// Failure code goes here\n}\nOrder order = orderCreateResult.Value;\n// success path here\n\n```\n\n### Error Handling\n\n#### Notify caller error with in built error types\n\nHandle Conflicts,\n\n```csharp\n public Return\u003cOrder\u003e CreateOrder(double totalAmount)\n {\n     // logic to apply the discount if total amount is \u003e 100\n     // Inventory says out of stock due to high demand\n\n     if (!inventoryManagement.AreEnoughStokesAvailable())\n     {\n          return Fault.Conflict(\"Not enough stockes in inventory.\");\n          //or\n          return Return\u003cOrder\u003e.Failure(Conflict.Create(\"Not enough stockes in inventory.\"));\n     }\n\n }\n```\n\n#### Other in-built error type available\n\n```csharp\n// all these take one string message arg and optinal description arg\nreturn Fault.NotFound();\nreturn Fault.InternalError();\nreturn Fault.ReturnError();\n```\n\n#### Type check errors for decision making\n\n```csharp\n\nReturn\u003cOrder\u003e result = GetOrder(id);\n\nif(result.IsFailure)\n{\n\n    if(result.IsErrorTypeOf\u003cNotFound\u003e())\n    {\n    // Not found logic goes here.\n    }\n\n    if(result.ErrorsContain\u003cNotFound\u003e())\n    {\n    // if error list contains Not found logic goes here.\n    }\n\n    if(result.Error.Is\u003cUnauthorized\u003e())\n    {\n    // Unauthorize logic goes here.\n    }\n\n    if(result.Errors.ContainsErrorType\u003cNotFound\u003e())\n    {\n    // Not found logic goes here.\n    }\n\n    if(result.Errors.ContainsErrorType\u003cOrderCreateError\u003e())\n    {\n    // if custom error type\n    }\n\n}\n\n\n\n```\n\n#### Handle Errors from caller method\n\n```csharp\n\n     Return\u003cOrder\u003e orderCreateResult = CreateOrder(100);\n\n     if (orderCreateResult.IsFailure)\n     {\n         // First error or only error of the list.\n         Fault error = orderCreateResult.Error;\n\n         // Read all errors returned.\n         IReadOnlyList\u003cFault\u003e errors = orderCreateResult.Errors;\n\n         // Error logic goes here\n     }\n\n     if (orderCreateResult.IsFailure)\n     {\n         // Pass errors to call stack\n         return orderCreateResult.Errors.ToList();\n     }\n \n```\n\n#### Define custom error types\n\nNeed to be inherited from Fault record\n\n```csharp\npublic record OrderCreationErrors : Fault\n{\n    public OrderCreationErrors(string message, string? description = null) : base(message, description) { }\n\n    public static OrderCreationErrors InvalidCustomerIdForOrderCreation =\u003e\n        new OrderCreationErrors(\"Could not find matching customer to the given customerId.\");\n\n    public static OrderCreationErrors CustomerBlacklisted =\u003e\n        new OrderCreationErrors(\"Customer with the given customerId has been blacklisted.\");\n}\n```\n\n#### Using Match\n\nMatch method can be used to trigger actions when some return is success or failure.\n\nTrigger actions with no return type.\n\n```csharp\nReturn\u003cOrder\u003e orderCreateResult = CreateOrder(100);\n\norderCreateResult.Match(\n    onSuccess: (value) =\u003e _logger.Info($\"{value.Id} Order created successfully.\"),\n    onFailure: (errors) =\u003e _logger.Error(\"Failed to create order.\")\n    );\n\n//Match first error of errors if failure.\norderCreateResult.MatchFirst(\n    onSuccess: (value) =\u003e _logger.Info($\"{value.Id} Order created successfully.\"),\n    onFailure: (error) =\u003e _logger.Error(\"Failed to create order.\")\n    );\n\norderCreateResult.MatchAsync(\n    onSuccess: async (value) =\u003e\n    {\n        // Simulating async process\n        await Task.Delay(100);\n        _logger.Info($\"{value.Id} Order created successfully.\");\n    },\n    onFailure: async (errors) =\u003e\n    {\n        // Simulating async process\n        await Task.Delay(100);\n        _logger.Error(\"Failed to create order.\");\n    });\n\n```\n\nMatch using TNextValue type, has return after match\n\n```csharp\n Return\u003cOrder\u003e orderCreateResult = Return\u003cOrder\u003e.Success(new Order());\n\n Response\u003cOrder\u003e response = orderCreateResult.Match\u003cResponse\u003cOrder\u003e\u003e(\n     onSuccess:(order) =\u003e new Response\u003cOrder\u003e() { Data = order },\n     onFailure:(errors) =\u003e new Response\u003cOrder\u003e() { Error = new { Error = errors.ToList() } });\n\n//gets first error of the list as the arg when failure.\n Response\u003cOrder\u003e response = orderCreateResult.MatchFirst\u003cResponse\u003cOrder\u003e\u003e(\n     onSuccess:(order) =\u003e new Response\u003cOrder\u003e() { Data = order },\n     onFailure:(error) =\u003e new Response\u003cOrder\u003e() { Error = new { Error = errors.ToList() } });\n\n\n Response\u003cOrder\u003e response = orderCreateResult.MatchAsync\u003cResponse\u003cOrder\u003e\u003e(\n     onSuccess: async (order) =\u003e {},\n     onFailure: async (errors) =\u003e {});\n\n//gets first error of the list as the arg when failure.\n Response\u003cOrder\u003e response = orderCreateResult.MatchFirstAsync\u003cResponse\u003cOrder\u003e\u003e(\n     onSuccess: async (order) =\u003e {},\n     onFailure: async (error) =\u003e {});\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeshansl%2Freturns","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdeshansl%2Freturns","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeshansl%2Freturns/lists"}