//----------------------------------------------------------------------- // // Copyright (c) aliasvault. All rights reserved. // Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information. // //----------------------------------------------------------------------- namespace AliasVault.Shared.Models.WebApi; using AliasVault.Shared.Models.Enums; /// /// Helper class for working with API error codes. /// public static class ApiErrorCodeHelper { /// /// Converts an ApiErrorCode enum value to its string representation. /// /// The error code to convert. /// String representation of the error code. public static string ToCode(this ApiErrorCode errorCode) { return errorCode.ToString(); } /// /// Creates an ApiErrorResponse with the specified error code and status. /// /// The error code. /// The HTTP status code. /// Optional additional details. /// ApiErrorResponse object. public static ApiErrorResponse CreateErrorResponse(ApiErrorCode errorCode, int statusCode, object? details = null) { return new ApiErrorResponse { Code = errorCode.ToCode(), Message = errorCode.ToCode(), // Clients will replace this with localized message StatusCode = statusCode, Details = details ?? new { }, Timestamp = DateTime.UtcNow, }; } /// /// Creates a ServerValidationErrorResponse with error codes instead of plain text. /// /// The error code. /// The HTTP status code. /// ServerValidationErrorResponse object. public static ServerValidationErrorResponse CreateValidationErrorResponse(ApiErrorCode errorCode, int status) { var code = errorCode.ToCode(); var errors = new Dictionary { { code, [code] }, }; return new ServerValidationErrorResponse { Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1", Title = code, Errors = errors, Status = status, TraceId = Guid.NewGuid().ToString(), }; } /// /// Creates a ServerValidationErrorResponse with multiple error codes. /// /// Array of error codes. /// The HTTP status code. /// ServerValidationErrorResponse object. public static ServerValidationErrorResponse CreateValidationErrorResponse(ApiErrorCode[] errorCodes, int status) { var errors = new Dictionary(); foreach (var errorCode in errorCodes) { var code = errorCode.ToCode(); errors.Add(code, new[] { code }); } var firstCode = errorCodes.Length > 0 ? errorCodes[0].ToCode() : ApiErrorCode.UNKNOWN_ERROR.ToCode(); return new ServerValidationErrorResponse { Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1", Title = firstCode, Errors = errors, Status = status, TraceId = Guid.NewGuid().ToString(), }; } }