我需要从azure函数返回服务器错误。
现在我使用InternalServerErrorResult()
实现相同的功能。它只发送错误代码,并且不能使用此功能发送响应/消息。
如何实现异常处理程序,其中错误代码和消息可以在azure函数中使用actionresult
一起发送
catch (Exception ex)
{
log.LogInformation("An error occured {0}" + ex);
//json = new Response(ex.StackTrace, AppConstants.ErrorCodes.SystemException).SerializeToString();
return (ActionResult)new InternalServerErrorResult();
}
这会在postman中返回一个空响应,错误为500
请注意,这是来自Microsoft.AspNetCore.Mvc
命名空间:
var result = new ObjectResult(new { error = "your error message here" })
{
StatusCode = 500
};
基于配置的格式化程序,它将序列化对象返回给客户端。对于JSON(它是默认值),它将返回以下内容:
{ "error" : "your error message here" }
要发送带有状态代码的消息,您可以使用return StatusCode(httpCode, message)
,这是一个ObjectResult。
例如:
return StatusCode(500, "An error occurred");
您还可以传递一个对象(使用HttpStatusCode枚举的示例):
return StatusCode((int)HttpStatusCode.InternalServerError, json);