【发布时间】:2017-06-09 23:31:18
【问题描述】:
我开发了一个从我的 ServiceStack 服务中抛出的自定义异常。状态代码和描述映射正确,但内部的“statusCode”值始终显示为“0”。
这是我实现异常的方式:
public class TestException : Exception, IHasStatusCode, IHasStatusDescription, IResponseStatusConvertible
{
private readonly int m_InternalErrorCode;
private readonly string m_ArgumentName;
private readonly string m_DetailedError;
public int StatusCode => 422;
public string StatusDescription => Message;
public TestException(int internalErrorCode, string argumentName, string detailedError)
: base("The request was semantically incorrect or was incomplete.")
{
m_InternalErrorCode = internalErrorCode;
m_ArgumentName = argumentName;
m_DetailedError = detailedError;
}
public ResponseStatus ToResponseStatus()
{
return new ResponseStatus
{
ErrorCode = StatusCode.ToString(),
Message = StatusDescription,
Errors = new List<ResponseError>
{
new ResponseError
{
ErrorCode = m_InternalErrorCode.ToString(),
FieldName = m_ArgumentName,
Message = m_DetailedError
}
}
};
}
}
当我从 ServiceStack 服务抛出异常时throw new TestException(123, "Thing in error", "Detailed error message");
当我在客户端(浏览器/邮递员等)中查看响应时,我得到一个 HTTP 状态代码 422,并按预期设置了相应的描述(原因/短语),但内容(当我在标题中指定 ContentType=application/json 时) ) 看起来像这样...
{
"statusCode": 0,
"responseStatus": {
"errorCode": "422",
"message": "The request was semantically incorrect or was incomplete.",
"stackTrace": "StackTrace ommitted for berivity",
"errors": [
{
"errorCode": "123",
"fieldName": "Thing in error",
"message": "Detailed error message"
}
]
}
}
正如您在上面的 json 响应中看到的,状态码是“0”。我的问题是 - 我如何设置这个值?我猜它应该和HTTP响应的一样(上面例子中的422)。
更新:感谢 Mythz 指出答案 我像这样更新了我的响应基类:
public abstract class ResponseBase : IHasResponseStatus, IHasStatusCode
{
private int m_StatusCode;
public int StatusCode
{
get
{
if (m_StatusCode == 0)
{
if (ResponseStatus != null)
{
if (int.TryParse(ResponseStatus.ErrorCode, out int code))
return code;
}
}
return m_StatusCode;
}
set
{
m_StatusCode = value;
}
}
public ResponseStatus ResponseStatus { get; set; }
}
【问题讨论】:
标签: c# servicestack .net-core http-status-codes