mirror of
https://github.com/scratchfoundation/scratch-link.git
synced 2025-08-28 22:39:42 -04:00
clean up JsonRpc2Exception a bit
This commit is contained in:
parent
7ec18de421
commit
bddf0dc50f
10 changed files with 47 additions and 37 deletions
|
@ -90,14 +90,14 @@ internal abstract class BLESession<TPeripheral, TPeripheralAddress, TUUID> : Per
|
|||
|
||||
if (filter.DataPrefix.Count != filter.Mask.Count)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams(
|
||||
$"length of data prefix ({filter.DataPrefix.Count}) does not match length of mask ({filter.Mask.Count})"));
|
||||
throw JsonRpc2Error.InvalidParams(
|
||||
$"length of data prefix ({filter.DataPrefix.Count}) does not match length of mask ({filter.Mask.Count})").ToException();
|
||||
}
|
||||
|
||||
if (filter.DataPrefix.Where((dataByte, index) => dataByte != (dataByte & filter.Mask[index])).Any())
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams(
|
||||
"invalid data filter: dataPrefix contains masked-out bits and will never match"));
|
||||
throw JsonRpc2Error.InvalidParams(
|
||||
"invalid data filter: dataPrefix contains masked-out bits and will never match").ToException();
|
||||
}
|
||||
|
||||
return filter;
|
||||
|
@ -119,18 +119,18 @@ internal abstract class BLESession<TPeripheral, TPeripheralAddress, TUUID> : Per
|
|||
if (args?.TryGetProperty("filters", out var jsonFilters) != true ||
|
||||
jsonFilters.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams("could not parse filters in discovery request"));
|
||||
throw JsonRpc2Error.InvalidParams("could not parse filters in discovery request").ToException();
|
||||
}
|
||||
|
||||
if (jsonFilters.GetArrayLength() < 1)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams("discovery request must include at least one filter"));
|
||||
throw JsonRpc2Error.InvalidParams("discovery request must include at least one filter").ToException();
|
||||
}
|
||||
|
||||
var filters = jsonFilters.EnumerateArray().Select(jsonFilter => this.ParseFilter(jsonFilter)).ToList();
|
||||
if (filters.Any(filter => filter.IsEmpty))
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams("discovery request includes empty filter"));
|
||||
throw JsonRpc2Error.InvalidParams("discovery request includes empty filter").ToException();
|
||||
}
|
||||
|
||||
this.AllowedServices.Clear();
|
||||
|
@ -139,7 +139,7 @@ internal abstract class BLESession<TPeripheral, TPeripheralAddress, TUUID> : Per
|
|||
{
|
||||
if (jsonOptionalServices.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams("could not parse optionalServices in discovery request"));
|
||||
throw JsonRpc2Error.InvalidParams("could not parse optionalServices in discovery request").ToException();
|
||||
}
|
||||
|
||||
var optionalServices = jsonOptionalServices.EnumerateArray().Select(this.GattHelpers.GetServiceUuid);
|
||||
|
@ -195,7 +195,7 @@ internal abstract class BLESession<TPeripheral, TPeripheralAddress, TUUID> : Per
|
|||
{
|
||||
if (args == null)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams("required parameter missing"));
|
||||
throw JsonRpc2Error.InvalidParams("required parameter missing").ToException();
|
||||
}
|
||||
|
||||
var endpoint = await this.GetEndpoint("write", (JsonElement)args, GattHelpers<TUUID>.BlockListStatus.ExcludeWrites);
|
||||
|
@ -220,7 +220,7 @@ internal abstract class BLESession<TPeripheral, TPeripheralAddress, TUUID> : Per
|
|||
{
|
||||
if (args == null)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams("required parameter missing"));
|
||||
throw JsonRpc2Error.InvalidParams("required parameter missing").ToException();
|
||||
}
|
||||
|
||||
var startNotifications = args?.TryGetProperty("startNotifications", out var jsonStartNotifications) == true && jsonStartNotifications.GetBoolean();
|
||||
|
@ -249,7 +249,7 @@ internal abstract class BLESession<TPeripheral, TPeripheralAddress, TUUID> : Per
|
|||
{
|
||||
if (args == null)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams("required parameter missing"));
|
||||
throw JsonRpc2Error.InvalidParams("required parameter missing").ToException();
|
||||
}
|
||||
|
||||
var endpoint = await this.GetEndpoint("startNotifications", (JsonElement)args, GattHelpers<TUUID>.BlockListStatus.ExcludeReads);
|
||||
|
@ -296,7 +296,7 @@ internal abstract class BLESession<TPeripheral, TPeripheralAddress, TUUID> : Per
|
|||
{
|
||||
if (args == null)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams("required parameter missing"));
|
||||
throw JsonRpc2Error.InvalidParams("required parameter missing").ToException();
|
||||
}
|
||||
|
||||
var endpoint = await this.GetEndpoint("stopNotifications", (JsonElement)args, GattHelpers<TUUID>.BlockListStatus.ExcludeReads);
|
||||
|
@ -342,7 +342,7 @@ internal abstract class BLESession<TPeripheral, TPeripheralAddress, TUUID> : Per
|
|||
filter.RequiredServices = new (jsonServices.EnumerateArray().Select(this.GattHelpers.GetServiceUuid));
|
||||
if (filter.RequiredServices.Count < 1)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams($"filter contains empty or invalid services list: {filter}"));
|
||||
throw JsonRpc2Error.InvalidParams($"filter contains empty or invalid services list: {filter}").ToException();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -359,7 +359,7 @@ internal abstract class BLESession<TPeripheral, TPeripheralAddress, TUUID> : Per
|
|||
|
||||
if (jsonFilter.TryGetProperty("serviceData", out _))
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.ApplicationError("filtering on serviceData is not currently supported"));
|
||||
throw JsonRpc2Error.ApplicationError("filtering on serviceData is not currently supported").ToException();
|
||||
}
|
||||
|
||||
return filter;
|
||||
|
@ -377,7 +377,7 @@ internal abstract class BLESession<TPeripheral, TPeripheralAddress, TUUID> : Per
|
|||
{
|
||||
if (!this.IsConnected)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.ApplicationError($"Peripheral is not connected for {errorContext}"));
|
||||
throw JsonRpc2Error.ApplicationError($"Peripheral is not connected for {errorContext}").ToException();
|
||||
}
|
||||
|
||||
var serviceId = endpointInfo.TryGetProperty("serviceId", out var jsonServiceId)
|
||||
|
@ -386,7 +386,7 @@ internal abstract class BLESession<TPeripheral, TPeripheralAddress, TUUID> : Per
|
|||
|
||||
if (EqualityComparer<TUUID>.Default.Equals(serviceId, default))
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams($"could not determine GATT service for {errorContext}"));
|
||||
throw JsonRpc2Error.InvalidParams($"could not determine GATT service for {errorContext}").ToException();
|
||||
}
|
||||
|
||||
var characteristicId = endpointInfo.TryGetProperty("characteristicId", out var jsonCharacteristicId)
|
||||
|
@ -395,22 +395,22 @@ internal abstract class BLESession<TPeripheral, TPeripheralAddress, TUUID> : Per
|
|||
|
||||
if (EqualityComparer<TUUID>.Default.Equals(characteristicId, default))
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams($"could not determine GATT characteristic for {errorContext}"));
|
||||
throw JsonRpc2Error.InvalidParams($"could not determine GATT characteristic for {errorContext}").ToException();
|
||||
}
|
||||
|
||||
if (this.GattHelpers.BlockList.TryGetValue(serviceId, out var serviceBlockStatus) && serviceBlockStatus.HasFlag(checkFlag))
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams($"service is blocked with {serviceBlockStatus}: {serviceId}"));
|
||||
throw JsonRpc2Error.InvalidParams($"service is blocked with {serviceBlockStatus}: {serviceId}").ToException();
|
||||
}
|
||||
|
||||
if (this.GattHelpers.BlockList.TryGetValue(characteristicId, out var characteristicBlockStatus) && characteristicBlockStatus.HasFlag(checkFlag))
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams($"characteristic is blocked with {serviceBlockStatus}: {serviceId}"));
|
||||
throw JsonRpc2Error.InvalidParams($"characteristic is blocked with {serviceBlockStatus}: {serviceId}").ToException();
|
||||
}
|
||||
|
||||
if (this.AllowedServices?.Any(allowedServiceId => serviceId.Equals(allowedServiceId)) != true)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams($"attempt to access unexpected service: {serviceId}"));
|
||||
throw JsonRpc2Error.InvalidParams($"attempt to access unexpected service: {serviceId}").ToException();
|
||||
}
|
||||
|
||||
return this.DoGetEndpoint(serviceId, characteristicId);
|
||||
|
|
|
@ -120,7 +120,7 @@ internal abstract class GattHelpers<TUUID>
|
|||
return this.CanonicalUuid(id);
|
||||
}
|
||||
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams($"unknown or invalid GATT name: {nameToken}"));
|
||||
throw JsonRpc2Error.InvalidParams($"unknown or invalid GATT name: {nameToken}").ToException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
@ -53,7 +53,7 @@ internal abstract class BTSession<TPeripheral, TPeripheralAddress> : PeripheralS
|
|||
|
||||
if (majorDeviceClass == null || minorDeviceClass == null)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams("majorDeviceClass and minorDeviceClass required"));
|
||||
throw JsonRpc2Error.InvalidParams("majorDeviceClass and minorDeviceClass required").ToException();
|
||||
}
|
||||
|
||||
this.ClearPeripherals();
|
||||
|
|
|
@ -30,7 +30,7 @@ public static class EncodingHelpers
|
|||
{
|
||||
if (!jsonBuffer.TryGetProperty("message", out var jsonMessage) || jsonMessage.ValueKind != JsonValueKind.String)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams("missing or invalid 'message' property"));
|
||||
throw JsonRpc2Error.InvalidParams("missing or invalid 'message' property").ToException();
|
||||
}
|
||||
|
||||
jsonBuffer.TryGetProperty("encoding", out var encoding);
|
||||
|
@ -42,7 +42,7 @@ public static class EncodingHelpers
|
|||
return messageBytes;
|
||||
}
|
||||
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.ParseError("failed to parse base64 message"));
|
||||
throw JsonRpc2Error.ParseError("failed to parse base64 message").ToException();
|
||||
}
|
||||
else if (encoding.ValueKind == JsonValueKind.Undefined || encoding.ValueKind == JsonValueKind.Null)
|
||||
{
|
||||
|
@ -50,7 +50,7 @@ public static class EncodingHelpers
|
|||
return Encoding.UTF8.GetBytes(jsonMessage.GetString());
|
||||
}
|
||||
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams($"unsupported encoding: {encoding}"));
|
||||
throw JsonRpc2Error.InvalidParams($"unsupported encoding: {encoding}").ToException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -69,7 +69,7 @@ public static class EncodingHelpers
|
|||
case null:
|
||||
return Encoding.UTF8.GetString(data);
|
||||
default:
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams($"unsupported encoding: {encoding}"));
|
||||
throw JsonRpc2Error.InvalidParams($"unsupported encoding: {encoding}").ToException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -100,4 +100,14 @@ public class JsonRpc2Error
|
|||
{
|
||||
return new JsonRpc2Error { Code = -32500, Message = "Application Error", Data = data };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wrap this error object in a <see cref="JsonRpc2Exception"/> object.
|
||||
/// Makes a new <see cref="JsonRpc2Exception"/> but does not make a new <see cref="JsonRpc2Error"/>.
|
||||
/// </summary>
|
||||
/// <returns>An new instance of <see cref="JsonRpc2Exception"/> wrapping this error.</returns>
|
||||
public JsonRpc2Exception ToException()
|
||||
{
|
||||
return new JsonRpc2Exception(this);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,7 +9,7 @@ using System;
|
|||
/// <summary>
|
||||
/// Exception class to hold a JSON-RPC 2.0 error.
|
||||
/// </summary>
|
||||
internal class JsonRpc2Exception : Exception
|
||||
public class JsonRpc2Exception : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JsonRpc2Exception"/> class to report a <see cref="JsonRpc2Error"/>.
|
||||
|
|
|
@ -50,14 +50,14 @@ public abstract class PeripheralSession<TPeripheral, TPeripheralAddress> : Sessi
|
|||
|
||||
if (peripheralId == null)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams("connect request must include peripheralId"));
|
||||
throw JsonRpc2Error.InvalidParams("connect request must include peripheralId").ToException();
|
||||
}
|
||||
|
||||
var peripheral = this.GetPeripheral(peripheralId);
|
||||
|
||||
if (peripheral == null)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidRequest(string.Format("peripheral {0} not available for connection", peripheralId)));
|
||||
throw JsonRpc2Error.InvalidRequest(string.Format("peripheral {0} not available for connection", peripheralId)).ToException();
|
||||
}
|
||||
|
||||
return await this.DoConnect(peripheral);
|
||||
|
|
|
@ -372,7 +372,7 @@ public class Session : IDisposable
|
|||
|
||||
private Task<object> HandleUnrecognizedMethod(string methodName, JsonElement? args)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.MethodNotFound(methodName));
|
||||
throw JsonRpc2Error.MethodNotFound(methodName).ToException();
|
||||
}
|
||||
|
||||
private async Task HandleRequest(JsonRpc2Request request, CancellationToken cancellationToken)
|
||||
|
|
|
@ -125,7 +125,7 @@ internal class MacBLESession : BLESession<CBPeripheral, NSUuid, CBUUID>
|
|||
var currentState = await this.GetSettledBluetoothState();
|
||||
if (currentState != BluetoothState.Available)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.ApplicationError("Bluetooth is not available"));
|
||||
throw JsonRpc2Error.ApplicationError("Bluetooth is not available").ToException();
|
||||
}
|
||||
|
||||
using (await this.filterLock.WaitDisposableAsync(this.CancellationToken))
|
||||
|
@ -148,7 +148,7 @@ internal class MacBLESession : BLESession<CBPeripheral, NSUuid, CBUUID>
|
|||
{
|
||||
if (this.connectedPeripheral != null)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidRequest("already connected or connecting"));
|
||||
throw JsonRpc2Error.InvalidRequest("already connected or connecting").ToException();
|
||||
}
|
||||
|
||||
this.cbManager.StopScan();
|
||||
|
@ -185,7 +185,7 @@ internal class MacBLESession : BLESession<CBPeripheral, NSUuid, CBUUID>
|
|||
if (this.connectedPeripheral != connectArgs.Peripheral)
|
||||
{
|
||||
this.connectedPeripheral = null;
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InternalError("did not connect to correct peripheral"));
|
||||
throw JsonRpc2Error.InternalError("did not connect to correct peripheral").ToException();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -67,7 +67,7 @@ internal class MacBTSession : BTSession<BluetoothDevice, BluetoothDeviceAddress>
|
|||
if (inquiryStatus != IOReturn.Success)
|
||||
{
|
||||
Debug.Print("Failed to start inquiry: {0}", inquiryStatus.ToDebugString());
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.ServerError(-32500, "Device inquiry failed to start"));
|
||||
throw JsonRpc2Error.ServerError(-32500, "Device inquiry failed to start").ToException();
|
||||
}
|
||||
|
||||
return Task.FromResult<object>(null);
|
||||
|
@ -99,7 +99,7 @@ internal class MacBTSession : BTSession<BluetoothDevice, BluetoothDeviceAddress>
|
|||
if (openChannelResult.Error != IOReturn.Success)
|
||||
{
|
||||
Debug.Print("Opening RFCOMM channel failed: {0}", openChannelResult.Error.ToDebugString());
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.ServerError(-32500, "Could not connect to RFCOMM channel."));
|
||||
throw JsonRpc2Error.ServerError(-32500, "Could not connect to RFCOMM channel.").ToException();
|
||||
}
|
||||
|
||||
// Connect is done already; don't wait for this run loop / session to complete.
|
||||
|
@ -128,7 +128,7 @@ internal class MacBTSession : BTSession<BluetoothDevice, BluetoothDeviceAddress>
|
|||
ushort shortLength = (ushort)buffer.Length;
|
||||
if (shortLength != buffer.Length)
|
||||
{
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InvalidParams("buffer too big to send"));
|
||||
throw JsonRpc2Error.InvalidParams("buffer too big to send").ToException();
|
||||
}
|
||||
|
||||
IOReturn writeResult;
|
||||
|
@ -150,7 +150,7 @@ internal class MacBTSession : BTSession<BluetoothDevice, BluetoothDeviceAddress>
|
|||
if (writeResult != IOReturn.Success)
|
||||
{
|
||||
Debug.Print("send error: {0}", writeResult.ToDebugString());
|
||||
throw new JsonRpc2Exception(JsonRpc2Error.InternalError("send encountered an error"));
|
||||
throw JsonRpc2Error.InternalError("send encountered an error").ToException();
|
||||
}
|
||||
|
||||
return shortLength;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue