Skip to content

Commit

Permalink
Merge pull request #34 from PandaTechAM/development
Browse files Browse the repository at this point in the history
Exception throw helpers are added
  • Loading branch information
HaikAsatryan committed Jun 22, 2024
2 parents 322e610 + 8b756b3 commit d6bff85
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 9 deletions.
37 changes: 34 additions & 3 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@ crafting detailed error responses suitable for both development and production e
exceptions.
* **Detailed Error Responses:** Generates verbose error messages, including stack traces for in-depth debugging in
development environments.
* **Environment-Sensitive Logging:** Provides flexible logging and response behavior based on visibility settings (`Public` or `Private`):
- **Private:** All exceptions are sent to the client as defined, and 4xx errors are logged as warnings while 5xx errors are logged as errors.
- **Public:** 4xx exceptions are sent to the client as defined, while 5xx errors are concealed with a generic message. Logging remains the same as in `Private`.
* **Environment-Sensitive Logging:** Provides flexible logging and response behavior based on visibility
settings (`Public` or `Private`):
- **Private:** All exceptions are sent to the client as defined, and 4xx errors are logged as warnings while 5xx
errors are logged as errors.
- **Public:** 4xx exceptions are sent to the client as defined, while 5xx errors are concealed with a generic
message. Logging remains the same as in `Private`.
* **Frontend-Friendly Error Messages:** Supports converting error messages to your desired case convention, facilitating
easier integration with frontend localization systems.
* **Standardized Error Responses:** Provides a standardized error response format, making it easier for frontend
Expand Down Expand Up @@ -116,6 +119,34 @@ The package automatically logs warnings or errors and provides crafted responses
* `InternalServerErrorException`
* `ServiceUnavailableException`

### Custom Exception Helper Methods

Using exception helpers:

```csharp
decimal? price = -10.5m;
BadRequestException.ThrowIfNullOrNegative(price, "price");

string? username = " ";
//For 400 Bad Request
BadRequestException.ThrowIfNullOrWhiteSpace(username, "username");
//For 404 Not Found
NotFoundException.ThrowIfNullOrWhiteSpace(username, "username");

List<string?>? tags = new List<string?> { "tag1", " ", null };
BadRequestException.ThrowIfNullOrWhiteSpace(tags, "tags");

object? user = null;
//For 400 Bad Request
BadRequestException.ThrowIfNull(user, "user");
//For 404 Not Found
NotFoundException.ThrowIfNull(user, "user");
```

These examples show how to use the `ThrowIfNullOrNegative`, `ThrowIfNullOrWhiteSpace`, and `ThrowIfNull` helper methods
from `BadRequestException` and `NotFoundException`. Adjust the object names and values according to your specific
application needs.

## Recommendations

* **Error Message Formatting:** It's recommended to use snake_case for error messages to aid frontend applications in
Expand Down
37 changes: 35 additions & 2 deletions src/ResponseCrafter/HttpExceptions/BadRequestException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,46 @@
public class BadRequestException : ApiException
{
private const string DefaultMessage = "the_request_was_invalid_or_cannot_be_otherwise_served.";

public BadRequestException(string message, Dictionary<string, string>? errors = null)
: base(400, message, errors)
{
}

public BadRequestException(Dictionary<string, string> errors)
: base(400,DefaultMessage, errors)
: base(400, DefaultMessage, errors)
{
}

public static void ThrowIfNullOrNegative(decimal? value, string? nameOfValue = null)
{
if (value is < 0 or null)
{
throw new BadRequestException($"{nameOfValue ?? "value"}_cannot_be_negative");
}
}

public static void ThrowIfNullOrWhiteSpace(string? value, string? nameOfValue = null)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new BadRequestException($"{nameOfValue ?? "value"}_cannot_be_null_or_whitespace");
}
}

public static void ThrowIfNullOrWhiteSpace(List<string?>? values, string? nameOfValue = null)
{
if (values is null || values.Count == 0 || values.Any(string.IsNullOrWhiteSpace))
{
throw new BadRequestException($"{nameOfValue ?? "value"}_cannot_contain_null_or_whitespace");
}
}

public static void ThrowIfNull(object? value, string? nameOfValue = null)
{
if (value is null)
{
throw new BadRequestException($"{nameOfValue ?? "value"}_cannot_be_null");
}
}
}
16 changes: 16 additions & 0 deletions src/ResponseCrafter/HttpExceptions/NotFoundException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,20 @@
public class NotFoundException(string message = NotFoundException.DefaultMessage) : ApiException(404, message)
{
private const string DefaultMessage = "the_requested_resource_was_not_found.";

public static void ThrowIfNullOrWhiteSpace(string? value, string? nameOfValue = null)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new NotFoundException($"{nameOfValue ?? "the_requested_resource"}_was_not_found.");
}
}

public static void ThrowIfNull(object? value, string? nameOfValue = null)
{
if (value is null)
{
throw new NotFoundException($"{nameOfValue ?? "the_requested_resource"}_was_not_found.");
}
}
}
8 changes: 4 additions & 4 deletions src/ResponseCrafter/ResponseCrafter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
<Copyright>MIT</Copyright>
<PackageIcon>pandatech.png</PackageIcon>
<PackageReadmeFile>Readme.md</PackageReadmeFile>
<Version>2.0.0</Version>
<Version>2.1.0</Version>
<PackageId>Pandatech.ResponseCrafter</PackageId>
<PackageTags>Pandatech, library, exception handler, exception, middleware, Api response</PackageTags>
<Title>ResponseCrafter</Title>
<Description>Handling exceptions, custom Dtos.</Description>
<RepositoryUrl>https://github.com/PandaTechAM/be-lib-response-crafter</RepositoryUrl>
<PackageReleaseNotes>Dropped support for EfCoreMagicQuery library</PackageReleaseNotes>
<PackageReleaseNotes>Exception throw helpers are added</PackageReleaseNotes>
</PropertyGroup>

<ItemGroup>
Expand All @@ -25,9 +25,9 @@
<ItemGroup>
<PackageReference Include="Humanizer" Version="2.14.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.6" />
<PackageReference Include="PandaTech.BaseConverter" Version="3.0.6" />
<PackageReference Include="PandaTech.BaseConverter" Version="4.0.3" />
<PackageReference Include="PandaTech.FluentImporter" Version="2.0.12" />
<PackageReference Include="Pandatech.GridifyExtensions" Version="1.1.0" />
<PackageReference Include="Pandatech.GridifyExtensions" Version="1.3.1" />
<PackageReference Include="PandaTech.ServiceResponse" Version="1.2.12" />
</ItemGroup>

Expand Down

0 comments on commit d6bff85

Please sign in to comment.