【问题标题】:how to handle an exception "Invalid file signature" in asp.net core?如何处理asp.net核心中的异常“无效文件签名”?
【发布时间】:2020-01-06 10:23:43
【问题描述】:

我正在使用 .txt 文件而不是使用 excel 文件,所以我应该得到 400 错误,但我得到 500 错误。我想捕获异常并发送带有适当响应正文的 400 响应代码。

[Route("file/")]
[AuthorizeFunction(AuthFunctions.Schema.Create)]
[HttpPost]
[ResponseType(typeof(Schema))]
public async Task<IActionResult> Create([FromBody] Guid fileId)
{
     var result = await _SchemaService.Create(fileId);
     return Created("GetSchema", new { id = result.Id }, result);
}

【问题讨论】:

    标签: c# asp.net-core .net-core asp.net-core-mvc entity-framework-core


    【解决方案1】:

    您可以使用此代码来捕获特定错误

    [Route("file/")]
    [AuthorizeFunction(AuthFunctions.Schema.Create)]
    [HttpPost]
    [ResponseType(typeof(Schema))]
    public async Task<IActionResult> Create([FromBody] Guid fileId)
    {
         try {
             var result = await _SchemaService.Create(fileId);
             return Created("GetSchema", new { id = result.Id }, result);
         }
         catch (Exception exc){
           if (exc.GetType().FullName == "Your_Exception_Name") 
           {
              // Check your exception name here
           }
       }
    }
    

    或

    catch(Exception ex)
    {
      if(ex.InnerException is ExceptionInstance)// exception instance type you want to check
      {
    
      }
    }
    

    更新

    您可以只使用catch(Exception ex) 处理一般异常,然后返回BadRequest()

    catch(Exception ex)
    {
      return BadRequest();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 2019-06-06
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多