While using a custom message handler, I keep encountering the following error on the API server side:
API Controller:-
[RoutePrefix("errors")]
public class ErrorController : ApiController
{
[HttpGet]
[Route("{id}")]
public IHttpActionResult GetClientEmailId(int id)
{
return this.Ok();
}
}
Custom Message Handler:-
public class ApiMessageHandler: DelegatingHandler
{
protected override async Task<HttpResponseMessage>
SendAsync(HttpRequestMessage request, CancellationToken
cancellationToken)
{
var logger = LogManager.GetLogger(this.GetType().FullName);
if (logger.IsDebugEnabled)
{
var requestMessage = await
request.Content.ReadAsByteArrayAsync();
var resTask = base.SendAsync(request,
cancellationToken).ContinueWith(
t =>
{
if (t.Exception != null)
{
throw t.Exception;
}
return t.Result;
},
cancellationToken);
byte[] responseMessage;
if (resTask.Result.IsSuccessStatusCode)
{
responseMessage = resTask.Result.Content != null
? await resTask.Result.Content.ReadAsByteArrayAsync()
: Encoding.UTF8.GetBytes(resTask.Result.ReasonPhrase);
}
else
{
responseMessage = Encoding.UTF8.GetBytes(resTask.Result.ReasonPhrase);
}
await this.Log(request, requestMessage, resTask.Result,
responseMessage, logger);
return resTask.Result;
}
var response = await base.SendAsync(request, cancellationToken);
return response;
}
when I called action method http://localhos:4200/errors/adf(pass string parameter instead of integer) then I got System.FormatException in Base.SendAsync method. The exception was thrown: 'System.FormatException' in mscorlib.dll Additional information: Input string was not in a correct format.
But this exception is not handled by GlobalException Handler.
It looks like a base.SendAsync method has swallowed this exception. How we can handle this exception and rethrow so GlobalException handler can handle this exception with proper message.
Thank you in advance.