This is repository for ExceptionHandling
opensource library.
ExceptionHandling
helps to convert thrown exceptions to valid json object.
This object contains:
- HTTP code;
- Error message.
dotnet add package Sterlyukin.ExceptionHandling
Create your custom exceptions that are derived from Exception
public sealed class UnauthorizedException : Exception
{
public UnauthorizedException(string message) : base(message)
{
}
}
public sealed class NotFoundException : Exception
{
public NotFoundException(string message) : base(message)
{
}
}
Register each exception with matching HTTP status code
app.AddExceptionHandling<UnauthorizedException>(HttpStatusCode.Unauthorized);
app.AddExceptionHandling<NotFoundException>(HttpStatusCode.NotFound);
Throw exceptions in your code and they will be translated to response with matching HTTP status code.
You shouldn't to tune library more. After this it is ready for using.
public sealed class Service
{
public void GetSuccess()
{
}
public void GetUnauthorized()
{
throw new UnauthorizedException("You are unauthorized");
}
public void GetNotFound()
{
throw new NotFoundException("Data wasn't found");
}
}
[ApiController]
[Route("api/[controller]")]
public class FakeController : ControllerBase
{
private readonly Service service;
public FakeController(Service service)
{
this.service = service ?? throw new ArgumentNullException(nameof(service));
}
[HttpGet("unauthorized")]
public IActionResult GetUnauthorized()
{
service.GetUnauthorized();
return Ok();
}
[HttpGet("not-found")]
public IActionResult GetNotFound()
{
service.GetNotFound();
return Ok();
}
}
Response from API endpoint will be in this format with the corresponding status code
HTTP Status Code = 401
{
"Code": 401,
"Message": "You are unauthorized"
}
Repository is opened for your contribution.
Improve it by creating Issues
and Pull requests
.
Pay attention that pull requests can be created only from issues.
Algorithm:
- Create an issue - describe what do you want to impore/fix in the library;
- Create new branch from
main
by patternissues_{issue number}
; - Create pull request to
main
branch; - Make sure that all checks passed successfully;
- Assign
sterlyukin
as reviewer of your pull-request; - Link issue to your PR;
- Wait for comments or approve;
- If your PR has some comments to fix - fix them and push to the branch again;
- Leave comments that you fixed under all remarks;
- When PR will be successfully closed - I will publish it to
nuget
.
CI/CD automated by Github Actions.
Build
and test
are launched on push to the branch.
Publish
to nuget launches manually in releases.