2017-09-06 41 views
0

在許多代碼重複操作的基礎上驗證屬性(基於模型狀態)時,我必須拋出自定義異常。在驗證特定操作參數時拋出自定義異常

這怎麼可以重構?

當前代碼示例

[HttpGet("{jobId}/employeeLog")] 
public async Task<IActionResult> GetFileLog(Guid jobId, 
    [FromQuery] Guid employeeId, 
    [SkipAndTopFromQuery] int? skip, 
    [SkipAndTopFromQuery] int? top, 
    [FromHeader(Name = "X-Correlation-ID")] string correlationId) 
{ 
    var employeeIdToValidate = ModelState["employeeId"]; 
    var jobIdToValidate = ModelState["jobId"]; 
    if (employeeIdToValidate == null || employeeIdToValidate != null && employeeIdToValidate.Errors.Any()) 
     throw new InvalidFileIdException(); 
    if (jobIdToValidate == null || jobIdToValidate != null && jobIdToValidate.Errors.Any()) 
     throw new InvalidApplicationIdException(); 
    if (!ModelState.IsValid) 
     return StatusCode((int)HttpStatusCode.BadRequest); 

    .... 
} 

回答

1

如果你想簡化您的如果語句,你可以使用Null Propagation Operator in C#

public async Task<IActionResult> GetFileLog(Guid jobId, 
    [FromQuery] Guid employeeId, 
    [SkipAndTopFromQuery] int? skip, 
    [SkipAndTopFromQuery] int? top, 
    [FromHeader(Name = "X-Correlation-ID")] string correlationId) 
{ 
    var employeeIdToValidate = ModelState["employeeId"]; 
    var jobIdToValidate = ModelState["jobId"]; 

    if (employeeIdToValidate?.Errors?.Any() ?? true) 
     throw new InvalidFileIdException(); 

    if (jobIdToValidate?.Errors?.Any() ?? true) 
     throw new InvalidApplicationIdException(); 

    if (!ModelState.IsValid) 
     return StatusCode((int)HttpStatusCode.BadRequest); 

    .... 
} 

此外,如果你的ModelState返回相同的對象,或對象使用通用界面,您可以將支票移入某種方法。

class GetFileLogValidatior: ValidatorBase { 

    public override void Validate(GetFileLogValidatiorContext context) { 

     var employeeIdToValidate = context.EmployeeIdToValidate; 
     var jobIdToValidate = context.JobIdToValidate; 

     if (employeeIdToValidate?.Errors?.Any() ?? true) 
      throw new InvalidFileIdException(); 

     if (jobIdToValidate?.Errors?.Any() ?? true) 
      throw new InvalidApplicationIdException(); 
    } 

} 

順便說一句,你可以通過創建某種類的像驗證從你的方法拆分您的驗證