2017-06-09 43 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

相關問題