Skip to content

Commit

Permalink
Create CoapException from CoapMessage
Browse files Browse the repository at this point in the history
  • Loading branch information
NZSmartie committed Dec 4, 2017
1 parent 30d06ee commit 30ea8d2
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/CoAPNet/CoapException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace CoAPNet
{
Expand Down Expand Up @@ -51,5 +52,24 @@ public CoapException(string message, Exception innerException, CoapMessageCode r
{
ResponseCode = responseCode;
}

public static CoapException FromCoapMessage(CoapMessage message, Exception innerExcpetion = null)
{
if (message == null)
throw new ArgumentNullException(nameof(message));

var errorMessage = string.Empty;
var contentFormat = message.Options.Get<Options.ContentFormat>();

if (contentFormat != null && message.Payload != null)
{
if (contentFormat.MediaType == Options.ContentFormatType.TextPlain)
errorMessage = System.Text.Encoding.UTF8.GetString(message.Payload);
else
errorMessage = string.Join(", ", message.Payload.Select(b => $"0x{b:X2}"));
}

return new CoapException(errorMessage, innerExcpetion, message.Code);
}
}
}

0 comments on commit 30ea8d2

Please sign in to comment.