[英]how to set response when i am using IActionResult in return type with error message?
enter image description here when try block send error to catch block it throw and response I got at frontend was {status:'error',error:500}.当尝试块发送错误以捕获它抛出的块并且我在前端得到的响应是 {status:'error',error:500} 时,在此处输入图像描述。 Please explain me what is going when I Re-throw in catch block.请解释一下当我重新放入 catch 块时发生了什么。 Is .NET is set response when I re-throw?当我重新抛出时,.NET 是否设置响应?
I want to set status message.我想设置状态消息。 how can I do?我能怎么做?
I want to set status message.我想设置状态消息。 how can I do?我能怎么做?
Well, you can bind custom status inside BadRequest()
or Any other response class result.那么,您可以在BadRequest()
或任何其他响应 class 结果中绑定自定义状态。 For instance:例如:
public async Task<IActionResult> DownloadAttachedFile()
{
try
{
//Your code
}
catch (Exception ex)
{
return BadRequest(new { StatusMessage = "Your Messaage", StatusCode = 400 });
}
}
Note: Here StatusMessage
, you can even concat your ex
message as well.注意:在这里StatusMessage
,你甚至可以连接你的ex
消息。 Can introduce new custom error class. You can also skip StatusCode = 400
because BadRequest
itself will return that code but if you want to fetch easily from your frontend you can set as well.可以引入新的自定义错误 class。您也可以跳过StatusCode = 400
,因为BadRequest
本身会返回该代码,但如果您想从前端轻松获取,也可以设置。
Output: Output:
In your frontend you would get the response as following:在您的前端,您会得到如下响应:
{
"statusMessage": "Your Messaage",
"statusCode": 400
}
In addition, you can always customize your response class based on your requirement.此外,您始终可以根据您的要求自定义您的回复 class。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.