CS2-145 Добавить специальный ArgumentInvalidException кастомной вылидации для замены ArgumentException

This commit is contained in:
Фролов 2022-01-18 11:04:15 +05:00
parent ae8b549617
commit 7a10d26ca6
10 changed files with 50 additions and 26 deletions

View File

@ -0,0 +1,15 @@
using System;
namespace AsbCloudApp.Exceptions
{
public class ArgumentInvalidException: Exception
{
public string ParamName { get; }
public ArgumentInvalidException(string message, string paramName = default)
:base(message)
{
ParamName = paramName;
}
}
}

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using AsbCloudApp.Exceptions;
using AsbCloudDb.Model;
using AsbSaubReport.Model;
using Microsoft.EntityFrameworkCore;
@ -38,7 +39,7 @@ namespace AsbCloudInfrastructure
idTelemetry = well?.IdTelemetry;
if (idTelemetry is null)
throw new ArgumentException($"Well {idWell} doesn't contain telemetry", nameof(idWell));
throw new ArgumentInvalidException($"Well {idWell} doesn't contain telemetry", nameof(idWell));
events = context.TelemetryEvents
.Where(e => e.IdTelemetry == idTelemetry)

View File

@ -1,4 +1,5 @@
using AsbCloudApp.Data;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Services;
using ClosedXML.Excel;
using ClosedXML.Excel.Drawings;
@ -95,7 +96,7 @@ namespace AsbCloudInfrastructure.Services
.ConfigureAwait(false);
if (fileInfo.IdCategory != idFileCategoryDrillingProgramItems)
throw new ArgumentException($"Этот метод допустим только для файлов-частей программы бурения idCategory=={idFileCategoryDrillingProgramItems}.", nameof(fileMarkDto));
throw new ArgumentInvalidException($"Этот метод допустим только для файлов-частей программы бурения idCategory=={idFileCategoryDrillingProgramItems}.", nameof(fileMarkDto));
var result = await fileService.CreateFileMarkAsync(fileMarkDto, idUser, token)
.ConfigureAwait(false);
@ -117,7 +118,7 @@ namespace AsbCloudInfrastructure.Services
.ConfigureAwait(false);
if (fileInfo.IdCategory != idFileCategoryDrillingProgramItems)
throw new ArgumentException($"Этот метод допустим только для файлов-частей программы бурения idCategory=={idFileCategoryDrillingProgramItems}.", nameof(idMark));
throw new ArgumentInvalidException($"Этот метод допустим только для файлов-частей программы бурения idCategory=={idFileCategoryDrillingProgramItems}.", nameof(idMark));
var result = await fileService.MarkFileMarkAsDeletedAsync(idMark, token)
.ConfigureAwait(false);

View File

@ -1,4 +1,5 @@
using AsbCloudApp.Data;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Mapster;
@ -65,7 +66,7 @@ namespace AsbCloudInfrastructure.Services
destinationFileName = Path.GetFileName(destinationFileName);
srcFilePath = Path.GetFullPath(srcFilePath);
if (!File.Exists(srcFilePath))
throw new ArgumentException($"file {srcFilePath} doesn't exist", nameof(srcFilePath));
throw new ArgumentInvalidException($"file {srcFilePath} doesn't exist", nameof(srcFilePath));
var sysFileInfo = new System.IO.FileInfo(srcFilePath);

View File

@ -1,4 +1,5 @@
using AsbCloudApp.Data;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
@ -78,9 +79,9 @@ namespace AsbCloudInfrastructure.Services
public Task<int> InsertAsync(int idWell, MeasureDto dto, CancellationToken token)
{
if (dto.IdCategory < 1)
throw new ArgumentException("wrong idCategory", nameof(dto));
throw new ArgumentInvalidException("wrong idCategory", nameof(dto));
if (dto.Data is null)
throw new ArgumentException("data.data is not optional", nameof(dto));
throw new ArgumentInvalidException("data.data is not optional", nameof(dto));
var timezone = wellService.GetTimezone(idWell);
var entity = dto.Adapt<Measure>();
entity.IdWell = idWell;
@ -92,11 +93,11 @@ namespace AsbCloudInfrastructure.Services
public async Task<int> UpdateAsync(int idWell, MeasureDto dto, CancellationToken token)
{
if (dto.Id < 1)
throw new ArgumentException("wrong id", nameof(dto));
throw new ArgumentInvalidException("wrong id", nameof(dto));
if (dto.IdCategory < 1)
throw new ArgumentException("wrong idCategory", nameof(dto));
throw new ArgumentInvalidException("wrong idCategory", nameof(dto));
if (dto.Data is null)
throw new ArgumentException("data.data is not optional", nameof(dto));
throw new ArgumentInvalidException("data.data is not optional", nameof(dto));
var entity = await db.Measures
.Where(m => m.Id == dto.Id && !m.IsDeleted)
@ -104,7 +105,7 @@ namespace AsbCloudInfrastructure.Services
.ConfigureAwait(false);
if (entity is null)
throw new ArgumentException("id doesn't exist", nameof(dto));
throw new ArgumentInvalidException("id doesn't exist", nameof(dto));
var timezone = wellService.GetTimezone(idWell);
@ -118,7 +119,7 @@ namespace AsbCloudInfrastructure.Services
public async Task<int> MarkAsDeleteAsync(int idWell, int idData, CancellationToken token)
{
if (idData < 1)
throw new ArgumentException("wrong id", nameof(idData));
throw new ArgumentInvalidException("wrong id", nameof(idData));
var entity = await db.Measures.Where(m => m.IdWell == idWell && m.Id == idData)
.FirstOrDefaultAsync(token)
@ -132,7 +133,7 @@ namespace AsbCloudInfrastructure.Services
public Task<int> DeleteAsync(int idWell, int idData, CancellationToken token)
{
if (idData < 1)
throw new ArgumentException("wrong id", nameof(idData));
throw new ArgumentInvalidException("wrong id", nameof(idData));
db.Measures.RemoveRange(db.Measures.Where(m => m.IdWell == idWell && m.Id == idData));
return db.SaveChangesAsync(token);
}

View File

@ -9,6 +9,7 @@ using Mapster;
using AsbCloudApp.Services;
using System;
using AsbCloudApp.Comparators;
using AsbCloudApp.Exceptions;
namespace AsbCloudInfrastructure.Services
{
@ -83,7 +84,7 @@ namespace AsbCloudInfrastructure.Services
var entities = await cacheUserRoles.WhereAsync(r => names.Contains(r.Caption), token)
.ConfigureAwait(false);
if (entities?.Count() != names.Count())
throw new ArgumentException("Invalid role names", nameof(names));
throw new ArgumentInvalidException("Invalid role names", nameof(names));
var dtos = entities.Select(Convert);
return dtos;
}

View File

@ -1,4 +1,5 @@
using AsbCloudApp.Data;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
@ -60,7 +61,7 @@ namespace AsbCloudInfrastructure.Services
{
var existingUser = await cacheUsers.FirstOrDefaultAsync(u => u.Login.ToLower() == login.ToLower(), token);
if (existingUser is not null)
throw new ArgumentException($"Login {login} is busy by {existingUser.MakeDisplayName()}, id{existingUser.Id}", nameof(login));
throw new ArgumentInvalidException($"Login {login} is busy by {existingUser.MakeDisplayName()}, id{existingUser.Id}", nameof(login));
}
public Task<int> InsertRangeAsync(IEnumerable<UserExtendedDto> newItems, CancellationToken token = default)
@ -91,7 +92,7 @@ namespace AsbCloudInfrastructure.Services
public async Task<int> UpdateAsync(int id, UserExtendedDto dto, CancellationToken token = default)
{
if (id <= 1)
throw new ArgumentException($"Invalid id {id}. You can't edit this user.", nameof(id));
throw new ArgumentInvalidException($"Invalid id {id}. You can't edit this user.", nameof(id));
var oldUser = await cacheUsers.FirstOrDefaultAsync(u=>u.Id == id, token);
if(oldUser.Login != dto.Login)
@ -104,7 +105,7 @@ namespace AsbCloudInfrastructure.Services
if (dto.Id == 0)
entity.Id = id;
else if (dto.Id != id)
throw new ArgumentException($"Invalid userDto.id it mast be 0 or {id}", nameof(dto));
throw new ArgumentInvalidException($"Invalid userDto.id it mast be 0 or {id}", nameof(dto));
var result = await cacheUsers.UpsertAsync(entity, token)
.ConfigureAwait(false);

View File

@ -1,4 +1,5 @@
using AsbCloudApp.Data;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using AsbCloudInfrastructure.Services.Cache;
@ -70,13 +71,13 @@ namespace AsbCloudInfrastructure.Services
public override async Task<int> InsertAsync(WellDto dto, CancellationToken token = default)
{
if (dto.IdWellType is < 1 or > 2)
throw new ArgumentException("Тип скважины указан неправильно.", nameof(dto));
throw new ArgumentInvalidException("Тип скважины указан неправильно.", nameof(dto));
if (dto.IdState is < 0 or > 2)
throw new ArgumentException("Текущее состояние работы скважины указано неправильно.", nameof(dto));
throw new ArgumentInvalidException("Текущее состояние работы скважины указано неправильно.", nameof(dto));
if (dto.Id != 0 && await Cache.ContainsAsync(w => w.Id == dto.Id, token))
throw new ArgumentException($"Нельзя повторно добавить скважину с id: {dto.Id}", nameof(dto));
throw new ArgumentInvalidException($"Нельзя повторно добавить скважину с id: {dto.Id}", nameof(dto));
var entity = Convert(dto);
@ -100,13 +101,13 @@ namespace AsbCloudInfrastructure.Services
CancellationToken token = default)
{
if (dto.IdWellType is < 1 or > 2)
throw new ArgumentException("Тип скважины указан неправильно.", nameof(dto));
throw new ArgumentInvalidException("Тип скважины указан неправильно.", nameof(dto));
if (dto.IdState is < 0 or > 2)
throw new ArgumentException("Текущее состояние работы скважины указано неправильно.", nameof(dto));
throw new ArgumentInvalidException("Текущее состояние работы скважины указано неправильно.", nameof(dto));
if(dto.Id != idWell)
throw new ArgumentException($"Нельзя поменять id для скважины: {idWell} => {dto.Id}.", nameof(dto));
throw new ArgumentInvalidException($"Нельзя поменять id для скважины: {idWell} => {dto.Id}.", nameof(dto));
var entity = Convert(dto);
@ -259,7 +260,7 @@ namespace AsbCloudInfrastructure.Services
{
var well = Cache.FirstOrDefault(c => c.Id == idWell);
if (well == null)
throw new ArgumentException($"idWell: {idWell} does not exist.", nameof(idWell));
throw new ArgumentInvalidException($"idWell: {idWell} does not exist.", nameof(idWell));
return GetTimezone(well);
}

View File

@ -28,6 +28,7 @@ namespace AsbCloudWebApi.Middlewares
var idUser = context.User.GetUserId();
if (idUser is null)
{
context.User = null;
await context.ForbidAsync();
return;
}

View File

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Http;
using AsbCloudApp.Exceptions;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Threading.Tasks;
@ -20,7 +21,7 @@ namespace AsbCloudWebApi.Middlewares
{
await next?.Invoke(context);
}
catch(ArgumentException ex)
catch(ArgumentInvalidException ex)
{
Console.WriteLine($"ArgumentException in {context.Request.Method}: {ex.Message}");
context.Response.Clear();
@ -42,7 +43,7 @@ namespace AsbCloudWebApi.Middlewares
}
}
private static string MakeJsonBody(ArgumentException ex)
private static string MakeJsonBody(ArgumentInvalidException ex)
{
object error = new { name = ex.ParamName, errors = new string[] { ex.Message } };
var buffer = System.Text.Json.JsonSerializer.Serialize(error);