json_error_clarity 0.2.0 copy "json_error_clarity: ^0.2.0" to clipboard
json_error_clarity: ^0.2.0 copied to clipboard

Transform cryptic JSON parsing errors into crystal-clear, actionable error messages. Perfect companion to json_annotation.

example/main.dart

// Run with: dart run example/main.dart
//
// Demonstrates what json_error_clarity actually changes: the error you get
// when a JSON payload does not match what your model expects.

import 'package:json_error_clarity/json_error_clarity.dart';

/// A payload with three of the most common real-world API mismatches:
/// a number sent as text, a bool sent as 0/1, and a snake_case key.
const _payload = <String, dynamic>{
  'id': '42', // should be int, arrived as String
  'name': 'Widget',
  'is_active': 1, // should be bool, arrived as int
  'tags': ['new', 7], // element 1 is not a String
};

void main() {
  _section('1. Type mismatch: int field, String value');
  _compare(
    before: () => _payload['id'] as int,
    after: () => _payload.getSafeInt('id'),
  );

  _section('2. Missing key: model says isActive, payload says is_active');
  _compare(
    before: () => _payload['isActive'] as bool,
    after: () => _payload.getSafeBool('isActive'),
  );

  _section('3. Bad element inside a list');
  _compare(
    before: () => (_payload['tags'] as List).cast<String>().toList(),
    after: () => _payload.getSafeList('tags', (v) => v as String),
  );

  _section('4. Validating a whole payload up front');
  print('--- With json_error_clarity ---');
  try {
    _payload.requireKeys(['id', 'name', 'isActive']);
    print('(no error)');
  } on FormatException catch (e) {
    print(e.message);
  }

  _section('5. When it works, it just returns the value');
  print("name    = ${_payload.getSafeString('name')}");
  print("tags[0] = ${_payload.getSafeList('tags', (v) => v.toString())[0]}");
  print("missing = ${_payload.getNullableSafeString('nickname')}");
}

/// Runs both versions of the same access and prints what each one tells you.
void _compare({
  required Object? Function() before,
  required Object? Function() after,
}) {
  print('--- Plain Dart ---');
  try {
    before();
    print('(no error)');
  } catch (e) {
    print(e);
  }

  print('\n--- With json_error_clarity ---');
  try {
    after();
    print('(no error)');
  } on FormatException catch (e) {
    print(e.message);
  }
}

void _section(String title) {
  print('\n${'=' * 72}\n$title\n${'=' * 72}');
}
1
likes
160
points
116
downloads

Documentation

API reference

Publisher

verified publisherkhokan.me

Weekly Downloads

Transform cryptic JSON parsing errors into crystal-clear, actionable error messages. Perfect companion to json_annotation.

Homepage
Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

args, json_annotation, meta, path

More

Packages that depend on json_error_clarity