如何处理asp.net核心中的异常“无效文件签名”?

时间:2019-09-03 13:37:37

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

我使用的是.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);
}

1 个答案:

答案 0 :(得分:2)

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

[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();
}