Sisusa.ReturnTypes.ToActionResult 1.0.0

dotnet add package Sisusa.ReturnTypes.ToActionResult --version 1.0.0                
NuGet\Install-Package Sisusa.ReturnTypes.ToActionResult -Version 1.0.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Sisusa.ReturnTypes.ToActionResult" Version="1.0.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Sisusa.ReturnTypes.ToActionResult --version 1.0.0                
#r "nuget: Sisusa.ReturnTypes.ToActionResult, 1.0.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Sisusa.ReturnTypes.ToActionResult as a Cake Addin
#addin nuget:?package=Sisusa.ReturnTypes.ToActionResult&version=1.0.0

// Install Sisusa.ReturnTypes.ToActionResult as a Cake Tool
#tool nuget:?package=Sisusa.ReturnTypes.ToActionResult&version=1.0.0                

Namespace: Sisusa.ReturnTypes.WebApi

This namespace contains classes and extensions to handle failures in a Web API by converting them into appropriate HTTP responses using ActionResult.


I would have loved to have this ship as part of the Sisusa.Common.RetunTypes package but hated cluttering up that package's dependency chain - this package has an obvious dependency on Microsoft.ApnetCore.Mvc and the Sisusa packages (Data.Contracts, ReturnTypes)

Class: FailureExtensionsWebApi

A static class providing extension methods for converting IFailure objects into ASP.NET Core ActionResult instances.


Method: ToActionResult(this IFailure failure)

Converts an IFailure object into an ActionResult representing the appropriate HTTP response.

Parameters
  • failure (IFailure): An object representing a failure. If null, a generic "No failure to convert." message is returned.
Returns
  • ActionResult:
    • A ProblemDetails object wrapped in ObjectResult, containing the HTTP status code, failure message, and details.
    • A fallback response if failure is null.
Key Functionality
  1. Extracts the InnerException from the failure object or assigns a generic exception message.
  2. Creates a ProblemDetails object with:
    • Status: Determined by GetStatusCodeFromException.
    • Title: The message from the failure.
    • Detail: Detailed exception information from GetMessageDetailsFromException.
  3. Returns the ProblemDetails object wrapped in an ObjectResult.

Private Method: GetMessageDetailsFromException(Exception ex)

Retrieves detailed information from an exception.

Parameters
  • ex (Exception): The exception to extract details from.
Returns
  • string: A detailed description of the exception including:
    • The message.
    • Inner exception message (if present).
    • Debug information (if DEBUG is enabled):
      • Source of the exception.
      • Stack trace.

Private Method: GetStatusCodeFromException(Exception ex)

Maps an exception type to an appropriate HTTP status code.

Parameters
  • ex (Exception): The exception to evaluate.
Returns
  • int: The HTTP status code corresponding to the exception.
Status Code Mappings
  • EntityNotFoundException: 404 Not Found
  • BadConnectionException: 503 Service Unavailable
  • UnauthorizedAccessException: 401 Unauthorized
  • DuplicateKeyException: 409 Conflict
  • ArgumentException: 400 Bad Request
  • NullReferenceException: 400 Bad Request
  • All other exceptions: 500 Internal Server Error

Key Features

  1. Graceful Error Handling:
    • Converts exceptions and failures into structured HTTP responses (ProblemDetails).
  2. Detailed Debug Information:
    • Includes stack trace and source information in debug mode.
  3. Custom Status Codes:
    • Uses GetStatusCodeFromException to map specific exceptions to HTTP status codes.
  4. Extensibility:
    • Designed to easily extend exception handling logic by adding new mappings in GetStatusCodeFromException.

Usage Example

var failure = new CustomFailure("Something went wrong.");
var result = failure.ToActionResult();

// Use 'result' as the response in a controller action.
return result;

Most probable use case - the use case I wrote the library for.

[HttpGet("/{id:int}")]
public ActionResult<User> GetOne([FromRoute]int id)
{
    return userService
            .FindById(id)
            .MatchReturn(
                user=>Ok(user),
                err => err.ToActionResult() 
            );
}

This documentation provides an overview of the code's purpose, functionality, and usage to assist developers in understanding and utilizing the FailureExtensionsWebApi class effectively.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.0 100 1/5/2025

- initial feature release, extension method added to IFailure