csharp 通过继承为每个Model添加一个restException

RestBase

1
2
3
4
public abstract class RestBase
{
    public GlobalError restException {get;set;}
}

如此, 此类的子类都有了类型为 GlobalErrorrestException 字段

在使用RestSharp进行REST请求时, 如果发生异常, 一般会将错误以 GlobalError 这样的统一的形式返回,那么在

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
            request.OnBeforeDeserialization = (resp) =>
            {
                if (((int)resp.StatusCode) >= 400)
                {
                    string restException = "{{ \"restException\" : {0} }}";  //注意这行, 修改了返回的内容
                    var content = resp.RawBytes.AsString(); //get the response content
                    var newJson = string.Format(restException, content);

                    resp.Content = null;
                    resp.RawBytes = Encoding.UTF8.GetBytes(newJson.ToString());
                }
            };
记录平时瞎折腾遇到的各种问题, 方便查找
使用 Hugo 构建
主题 Stack 3.29.0Jimmy 设计