Skip to content

Commit 830e02c

Browse files
committed
Throw a more helpful error when a constructor is missing
Fixes #7
1 parent 189ccda commit 830e02c

File tree

4 files changed

+26
-1
lines changed

4 files changed

+26
-1
lines changed

json_serializable/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## 0.2.4+1
2+
3+
* Throw a more helpful error when a constructor is missing.
4+
15
## 0.2.4
26

37
* Moved the annotations in `annotations.dart` to `package:json_annotations`.

json_serializable/lib/src/json_serializable_generator.dart

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,10 @@ void $toJsonMapHelperName(String key, dynamic value) {
244244
// Get the default constructor
245245
// TODO: allow overriding the ctor used for the factory
246246
var ctor = classElement.unnamedConstructor;
247+
if (ctor == null) {
248+
throw new UnsupportedError(
249+
'The class `${classElement.name}` has no default constructor.');
250+
}
247251

248252
var ctorArguments = <ParameterElement>[];
249253
var ctorNamedArguments = <ParameterElement>[];

json_serializable/pubspec.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
name: json_serializable
2-
version: 0.2.4
2+
version: 0.2.4+1
33
author: Dart Team <misc@dartlang.org>
44
description: Generates utilities to aid in serializing to/from JSON.
55
homepage: https://github.com/dart-lang/json_serializable

json_serializable/test/json_serializable_test.dart

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,15 @@ abstract class _$OrderSerializerMixin {
208208
expect(output, contains("$toJsonMapHelperName('str', str);"));
209209
});
210210
});
211+
212+
test('missing default ctor with a factory', () async {
213+
expect(
214+
() => _runForElementNamed('NoCtorClass'),
215+
throwsA(new FeatureMatcher<UnsupportedError>(
216+
'message',
217+
(e) => e.message,
218+
'The class `NoCtorClass` has no default constructor.')));
219+
});
211220
}
212221

213222
const _generator = const JsonSerializableGenerator();
@@ -349,4 +358,12 @@ class IncludeIfNullOverride {
349358
int number;
350359
String str;
351360
}
361+
362+
// https://github.com/dart-lang/json_serializable/issues/7 regression
363+
@JsonSerializable()
364+
class NoCtorClass {
365+
final int member;
366+
367+
factory TestDoneEvent.fromJson(Map<String, dynamic> json) => null;
368+
}
352369
''';

0 commit comments

Comments
 (0)