OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 library json_rpc_2.exception; |
| 6 |
| 7 import '../error_code.dart' as error_code; |
| 8 |
| 9 /// An exception from a JSON-RPC server that can be translated into an error |
| 10 /// response. |
| 11 class RpcException implements Exception { |
| 12 /// The error code. |
| 13 /// |
| 14 /// All non-negative error codes are available for use by application |
| 15 /// developers. |
| 16 final int code; |
| 17 |
| 18 /// The error message. |
| 19 /// |
| 20 /// This should be limited to a concise single sentence. Further information |
| 21 /// should be supplied via [data]. |
| 22 final String message; |
| 23 |
| 24 /// Extra application-defined information about the error. |
| 25 /// |
| 26 /// This must be a JSON-serializable object. If it's a [Map] without a |
| 27 /// `"request"` key, a copy of the request that caused the error will |
| 28 /// automatically be injected. |
| 29 final data; |
| 30 |
| 31 RpcException(this.code, this.message, {this.data}); |
| 32 |
| 33 /// An exception indicating that the method named [methodName] was not found. |
| 34 /// |
| 35 /// This should usually be used only by fallback handlers. |
| 36 RpcException.methodNotFound(String methodName) |
| 37 : this(error_code.METHOD_NOT_FOUND, 'Unknown method "$methodName".'); |
| 38 |
| 39 /// An exception indicating that the parameters for the requested method were |
| 40 /// invalid. |
| 41 /// |
| 42 /// Methods can use this to reject requests with invalid parameters. |
| 43 RpcException.invalidParams(String message) |
| 44 : this(error_code.INVALID_PARAMS, message); |
| 45 |
| 46 /// Converts this exception into a JSON-serializable object that's a valid |
| 47 /// JSON-RPC 2.0 error response. |
| 48 serialize(request) { |
| 49 var modifiedData; |
| 50 if (data is Map && !data.containsKey('request')) { |
| 51 modifiedData = new Map.from(data); |
| 52 modifiedData['request'] = request; |
| 53 } else if (data == null) { |
| 54 modifiedData = {'request': request}; |
| 55 } |
| 56 |
| 57 var id = request is Map ? request['id'] : null; |
| 58 if (id is! String && id is! num) id = null; |
| 59 return { |
| 60 'jsonrpc': '2.0', |
| 61 'error': {'code': code, 'message': message, 'data': modifiedData}, |
| 62 'id': id |
| 63 }; |
| 64 } |
| 65 } |
OLD | NEW |