Branch | Build status |
---|---|
master | |
develop |
With the usage of Exception package, you can define Exception mapper and send it as a response.
dotnet add package Joint.Exception
- Joint
- Open.Serialization.Json.Newtonsoft
- Open.Serialization.Json.System
- Open.Serialization.Json.Utf8Json
Create your own exceptions separated by structure(DomainException
, AppException
, InfrastructureException
) or if you don't have structure use DefaultException
.
public class EmptyAccessTokenException : DomainException
{
public override string Code { get; } = "empty_access_token";
public override HttpStatusCode StatusCodes { get; } = HttpStatusCode.BadRequest;
public EmptyAccessTokenException() : base("Empty access token.")
{
}
}
public class UserNotFoundException : AppException
{
public override string Code { get; } = "user_not_found";
public override HttpStatusCode StatusCodes { get; } = HttpStatusCode.NotFound;
public Guid UserId { get; }
public UserNotFoundException(Guid userId) : base($"User with ID: '{userId}' was not found.")
{
UserId = userId;
}
}
public class UserNotFoundException : DefaultException
{
public override string Code { get; } = "user_not_found";
public override HttpStatusCode StatusCodes { get; } = HttpStatusCode.NotFound;
public Guid UserId { get; }
public UserNotFoundException(Guid userId) : base($"User with ID: '{userId}' was not found.")
{
UserId = userId;
}
}
Create dedicated ExceptionToResponseMapper
class that implements IExceptionToResponseMapper
interface with Map()
method:
public ExceptionResponse Map(Exception exception)
=> exception switch
{
DomainException ex => new ExceptionResponse(new { code = ex.Code, reason = ex.Message }, ex.StatusCodes),
AppException ex => new ExceptionResponse(new { code = ex.Code, reason = ex.Message }, ex.StatusCodes),
InfrastructureException ex => new ExceptionResponse(new { code = ex.Code, reason = ex.Message }, ex.StatusCodes),
_ => new ExceptionResponse(new { code = "error", reason = "There was an error." }, HttpStatusCode.BadRequest)
};
Extend IJointBuilder
with AddErrorHandler<T>()
that will register the required services.
public static IJointBuilder RegisterJoint(this IJointBuilder builder)
{
builder.AddErrorHandler<>()
// Other services.
return builder;
}
Then, invoke UseErrorHandler()
extension from IApplicationBuilder
.
public static IApplicationBuilder UseJoint(this IApplicationBuilder app)
{
app.UseErrorHandler();
// Other services.
return app;
}