Skip to content

Commit

Permalink
Made the "ExceptionHook" constructor parameter and field into an "Err…
Browse files Browse the repository at this point in the history
…orOnCapture" property.
  • Loading branch information
asbjornu committed Dec 10, 2014
1 parent d3bad49 commit f2313d0
Show file tree
Hide file tree
Showing 2 changed files with 123 additions and 88 deletions.
201 changes: 115 additions & 86 deletions src/app/SharpRaven/RavenClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,15 @@ public class RavenClient : IRavenClient
{
private readonly Dsn currentDsn;
private readonly IJsonPacketFactory jsonPacketFactory;
private readonly Action<Exception> exceptionHook;


/// <summary>
/// Initializes a new instance of the <see cref="RavenClient" /> class.
/// </summary>
/// <param name="dsn">The Data Source Name in Sentry.</param>
/// <param name="jsonPacketFactory">The optional factory that will be used to create the <see cref="JsonPacket" /> that will be sent to Sentry.</param>
/// <param name="exceptionHook">Hook in case of exceptions thrown during send</param>
public RavenClient(string dsn, IJsonPacketFactory jsonPacketFactory = null, Action<Exception> exceptionHook = null)
: this(new Dsn(dsn), jsonPacketFactory, exceptionHook)
public RavenClient(string dsn, IJsonPacketFactory jsonPacketFactory = null)
: this(new Dsn(dsn), jsonPacketFactory)
{
}

Expand All @@ -74,21 +72,20 @@ public RavenClient(string dsn, IJsonPacketFactory jsonPacketFactory = null, Acti
/// </summary>
/// <param name="dsn">The Data Source Name in Sentry.</param>
/// <param name="jsonPacketFactory">The optional factory that will be used to create the <see cref="JsonPacket" /> that will be sent to Sentry.</param>
/// <param name="exceptionHook">Hook in case of exceptions thrown during send</param>
/// <exception cref="System.ArgumentNullException">dsn</exception>
public RavenClient(Dsn dsn, IJsonPacketFactory jsonPacketFactory = null, Action<Exception> exceptionHook = null)
public RavenClient(Dsn dsn, IJsonPacketFactory jsonPacketFactory = null)
{
if (dsn == null)
throw new ArgumentNullException("dsn");

this.currentDsn = dsn;
this.jsonPacketFactory = jsonPacketFactory ?? new JsonPacketFactory();
this.exceptionHook = exceptionHook;

Logger = "root";
Timeout = TimeSpan.FromSeconds(5);
}


/// <summary>
/// Enable Gzip Compression?
/// Defaults to <c>false</c>.
Expand Down Expand Up @@ -123,6 +120,17 @@ public Dsn CurrentDsn
public TimeSpan Timeout { get; set; }


/// <summary>
/// Gets or sets the <see cref="Action"/> to execute if an error occurs when executing
/// <see cref="CaptureException"/> or <see cref="CaptureMessage"/>.
/// </summary>
/// <value>
/// The <see cref="Action"/> to execute if an error occurs when executing
/// <see cref="CaptureException"/> or <see cref="CaptureMessage"/>.
/// </value>
public Action<Exception> ErrorOnCapture { get; set; }


/// <summary>
/// Captures the <see cref="Exception" />.
/// </summary>
Expand All @@ -140,13 +148,20 @@ public string CaptureException(Exception exception,
IDictionary<string, string> tags = null,
object extra = null)
{
JsonPacket packet = this.jsonPacketFactory.Create(this.currentDsn.ProjectID,
exception,
message,
level,
tags,
extra);
return Send(packet, CurrentDsn);
try
{
JsonPacket packet = this.jsonPacketFactory.Create(this.currentDsn.ProjectID,
exception,
message,
level,
tags,
extra);
return Send(packet, CurrentDsn);
}
catch (Exception sendException)
{
return HandleException(sendException);
}
}


Expand All @@ -165,8 +180,55 @@ public string CaptureMessage(SentryMessage message,
Dictionary<string, string> tags = null,
object extra = null)
{
JsonPacket packet = this.jsonPacketFactory.Create(CurrentDsn.ProjectID, message, level, tags, extra);
return Send(packet, CurrentDsn);
try
{
JsonPacket packet = this.jsonPacketFactory.Create(CurrentDsn.ProjectID, message, level, tags, extra);
return Send(packet, CurrentDsn);
}
catch (Exception sendException)
{
return HandleException(sendException);
}
}


private string HandleException(Exception exception)
{
try
{
if (ErrorOnCapture != null)
{
ErrorOnCapture(exception);
return null;
}

Console.ForegroundColor = ConsoleColor.Red;
Console.Write("[ERROR] ");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(exception);

WebException webException = exception as WebException;
if (webException == null || webException.Response == null)
return null;

string messageBody;
using (Stream stream = webException.Response.GetResponseStream())
{
if (stream == null)
return null;

using (StreamReader sw = new StreamReader(stream))
messageBody = sw.ReadToEnd();
}

Console.WriteLine("[MESSAGE BODY] " + messageBody);
}
catch (Exception onErrorException)
{
Console.WriteLine(onErrorException);
}

return null;
}


Expand All @@ -182,89 +244,56 @@ protected virtual string Send(JsonPacket packet, Dsn dsn)
{
packet.Logger = Logger;

try
{
var request = (HttpWebRequest) WebRequest.Create(dsn.SentryUri);
request.Timeout = (int) Timeout.TotalMilliseconds;
request.ReadWriteTimeout = (int) Timeout.TotalMilliseconds;
request.Method = "POST";
request.Accept = "application/json";
request.Headers.Add("X-Sentry-Auth", PacketBuilder.CreateAuthenticationHeader(dsn));
request.UserAgent = PacketBuilder.UserAgent;

if (Compression)
{
request.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");
request.AutomaticDecompression = DecompressionMethods.Deflate;
request.ContentType = "application/octet-stream";
}
else
request.ContentType = "application/json; charset=utf-8";
var request = (HttpWebRequest) WebRequest.Create(dsn.SentryUri);
request.Timeout = (int) Timeout.TotalMilliseconds;
request.ReadWriteTimeout = (int) Timeout.TotalMilliseconds;
request.Method = "POST";
request.Accept = "application/json";
request.Headers.Add("X-Sentry-Auth", PacketBuilder.CreateAuthenticationHeader(dsn));
request.UserAgent = PacketBuilder.UserAgent;

/*string data = packet.ToString(Formatting.Indented);
Console.WriteLine(data);*/
if (Compression)
{
request.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");
request.AutomaticDecompression = DecompressionMethods.Deflate;
request.ContentType = "application/octet-stream";
}
else
request.ContentType = "application/json; charset=utf-8";

string data = packet.ToString(Formatting.None);
/*string data = packet.ToString(Formatting.Indented);
Console.WriteLine(data);*/

if (LogScrubber != null)
data = LogScrubber.Scrub(data);
string data = packet.ToString(Formatting.None);

// Write the messagebody.
using (Stream s = request.GetRequestStream())
{
if (Compression)
GzipUtil.Write(data, s);
else
{
using (StreamWriter sw = new StreamWriter(s))
sw.Write(data);
}
}
if (LogScrubber != null)
data = LogScrubber.Scrub(data);

using (HttpWebResponse wr = (HttpWebResponse) request.GetResponse())
using (Stream responseStream = wr.GetResponseStream())
// Write the messagebody.
using (Stream s = request.GetRequestStream())
{
if (Compression)
GzipUtil.Write(data, s);
else
{
if (responseStream == null)
return null;

using (StreamReader sr = new StreamReader(responseStream))
{
string content = sr.ReadToEnd();
var response = JsonConvert.DeserializeObject<dynamic>(content);
return response.id;
}
using (StreamWriter sw = new StreamWriter(s))
sw.Write(data);
}
}
catch (Exception exception)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("[ERROR] ");
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(exception);

WebException webException = exception as WebException;
if (webException != null && webException.Response != null)
{
string messageBody;
using (Stream stream = webException.Response.GetResponseStream())
{
if (stream == null)
return null;

using (StreamReader sw = new StreamReader(stream))
messageBody = sw.ReadToEnd();
}

Console.WriteLine("[MESSAGE BODY] " + messageBody);
}
using (HttpWebResponse wr = (HttpWebResponse) request.GetResponse())
using (Stream responseStream = wr.GetResponseStream())
{
if (responseStream == null)
return null;

if (exceptionHook != null)
using (StreamReader sr = new StreamReader(responseStream))
{
exceptionHook(exception);
string content = sr.ReadToEnd();
var response = JsonConvert.DeserializeObject<dynamic>(content);
return response.id;
}
}

return null;
}

#region Deprecated Methods
Expand Down
10 changes: 8 additions & 2 deletions src/tests/SharpRaven.UnitTests/Integration/CaptureTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,10 @@ public void CaptureException_CanLogException_If_Send_Fails()

Exception hookedException = null;

this.ravenClient = new RavenClient(dsnUri, null, exp => hookedException = exp);
this.ravenClient = new RavenClient(dsnUri)
{
ErrorOnCapture = exp => hookedException = exp
};

PrintInfo("In test client change!");
PrintInfo("Sentry Uri: " + this.ravenClient.CurrentDsn.SentryUri);
Expand Down Expand Up @@ -272,7 +275,10 @@ public void CaptureMessage__CanLogException_If_Send_Fails()

Exception hookedException = null;

ravenClient = new RavenClient(dsnUri, null, exp => hookedException = exp);
ravenClient = new RavenClient(dsnUri)
{
ErrorOnCapture = exp => hookedException = exp
};

PrintInfo("In test client change!");
PrintInfo("Sentry Uri: " + this.ravenClient.CurrentDsn.SentryUri);
Expand Down

0 comments on commit f2313d0

Please sign in to comment.