![](/img/trans.png)
[英]How to handle On Exception in the base controller of asp.net core?
[英]how to handle an exception "Invalid file signature" in asp.net 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);
}
您可以使用此代碼來捕獲特定錯誤
[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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.