我已经开发了一个自定义异常,我从ServiceStack服务中抛出异常。正确映射状态代码和描述,但内部状态代码和描述是正确的。值始终显示为' 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响应中所看到的,状态代码为&#39; 0&#39;。我的问题是 - 如何设置此值?我猜它应该与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; }
}
答案 0 :(得分:2)
ServiceStack仅填充错误响应中的ResponseStatus
DTO,statusCode
属性里面您的响应DTO是ServiceStack不支持的无关属性(可能是on your Response DTO)处理。自定义例外中实现的StatusCode
界面中的IHasStatusCode
属性仅用于填充HTTP Status Code。