CustomErrorMessageDelegatingHandler.cs
2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using HHECS.API.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace HHECS.API.Common
{
/// <summary>
/// 消息代理处理,用来捕获特殊的异常信息(这些异常不会被全局的异常filter捕获,这些异常应是在异常filter之前就已经发生并处理了)
/// </summary>
public class CustomErrorMessageDelegatingHandler: DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((responseToCompleteTask) =>
{
HttpResponseMessage response = responseToCompleteTask.Result;
HttpError error = null;
if (response.TryGetContentValue<HttpError>(out error))
{
//添加自定义错误处理
//error.Message = "Your Customized Error Message";
}
if (error != null)
{
var setting = new JsonSerializerSettings
{
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
};
//获取抛出自定义异常,有拦截器统一解析
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
{
//封装处理异常信息,返回指定JSON对象
Content = new StringContent(JsonConvert.SerializeObject(new ApiResultModel(HttpStatusCode.NotFound, null, error.Message), Formatting.None, setting)),
ReasonPhrase = "Exception"
});
}
else
{
return response;
}
});
}
}
}