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