2017-06-09 45 views
2

我开发了一个自定义的异常,我从我的ServiceStack服务抛出。状态码和说明映射正确,但内部的'statusCode'值始终显示为'0'。如何设置ServiceStack ResponseStatus StatusCode?

下面是我已经实现了我的异常:

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");
我得到的422用相应的描述HTTP状态码(原因/短语)当我查看我的客户端(浏览器/邮递员等)响应时设置的预期,但内容(当我指定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; } 
} 

回答

2

ServiceStack仅填充ResponseStatus DTO的错误响应,该statusCode财产您的Response DTO是ServiceStack无法处理的无关属性(可能为on your Response DTO)。自定义例外中实现的IHasStatusCode接口中的StatusCode属性仅用于填充HTTP Status Code

+0

啊,你说得对,它来自哪里。我的答复DTO实现IHasStatusCode并具有属性'公共ResponseStatus ResponseStatus {get;组; }' - 所以servicestack必须使用ResponseStatus填充我的Dto,并省略StatusCode。如果状态码尚未设置,我已经更改了我的响应基类以解析错误代码,现在它正在拾取正确的值。谢谢! – Jay

相关问题