Skip to content

Commit c49d2c4

Browse files
committed
fix(api): improve error handling for invalid JSON body
Adds a specific error handler for `CheckedFromJsonException` to return a 400 Bad Request instead of a generic 500 Internal Server Error when deserialization fails due to invalid client input. This provides more accurate feedback to API clients when they send a request body that is missing required fields or contains incorrect data types.
1 parent dbae817 commit c49d2c4

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

lib/src/middlewares/error_handler.dart

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import 'dart:io';
55

66
import 'package:dart_frog/dart_frog.dart';
77
import 'package:ht_shared/ht_shared.dart';
8+
import 'package:json_annotation/json_annotation.dart';
89

910
/// Middleware that catches errors and converts them into
1011
/// standardized JSON responses.
@@ -26,6 +27,21 @@ Middleware errorHandler() {
2627
'error': {'code': errorCode, 'message': e.message},
2728
},
2829
);
30+
} on CheckedFromJsonException catch (e, stackTrace) {
31+
// Handle json_serializable validation errors. These are client errors.
32+
final field = e.key ?? 'unknown';
33+
final message = 'Invalid request body: Field "$field" has an '
34+
'invalid value or is missing. ${e.message}';
35+
print('CheckedFromJsonException Caught: $e\n$stackTrace');
36+
return Response.json(
37+
statusCode: HttpStatus.badRequest, // 400
38+
body: {
39+
'error': {
40+
'code': 'invalidField',
41+
'message': message,
42+
},
43+
},
44+
);
2945
} on FormatException catch (e, stackTrace) {
3046
// Handle data format/parsing errors (often indicates bad client input)
3147
print('FormatException Caught: $e\n$stackTrace'); // Log for debugging

pubspec.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ dependencies:
3434
ht_shared:
3535
git:
3636
url: https://github.com/headlines-toolkit/ht-shared.git
37-
37+
json_annotation: ^4.9.0
3838
logging: ^1.3.0
3939
meta: ^1.16.0
4040
mongo_dart: ^0.10.5

0 commit comments

Comments
 (0)