101 lines
3.0 KiB
Dart

import 'dart:convert';
import 'package:backend_dart/domain/errors/error_code.dart';
import 'package:backend_dart/domain/interface/error.dart';
import 'package:fpdart/fpdart.dart';
import 'package:shelf/shelf.dart';
extension TaskEitherResponseExtensions
on TaskEither<IError, Map<String, dynamic>> {
Task<Response> toResponse() => match(
(left) => ResponseHelpers.fromError(left),
(right) => ResponseHelpers.jsonOk(right),
);
}
extension TaskEitherResponseExtensionsFromString on TaskEither<IError, String> {
Task<Response> toResponse() => match(
(left) => ResponseHelpers.fromError(left),
(right) => Response.ok(right),
);
}
class ResponseHelpers {
/// Sendet eine JSON-Antwort mit einem 200-Statuscode
static Response jsonOk(Map<String, dynamic> data) {
return Response.ok(
jsonEncode(data),
headers: {'Content-Type': 'application/json'},
);
}
/// Sendet eine JSON-Antwort mit einem spezifischen Statuscode
static Response jsonWithStatus(Map<String, dynamic> data, int statusCode) {
return Response(
statusCode,
body: jsonEncode(data),
headers: {'Content-Type': 'application/json'},
);
}
/// Sendet eine JSON-Antwort für einen Fehler (z. B. 404 oder 500)
static Response jsonError(String message, {int statusCode = 500}) {
return Response(
statusCode,
body: jsonEncode({'error': message}),
headers: {'Content-Type': 'application/json'},
);
}
/// Sendet eine einfache Textantwort
static Response textResponse(String message, {int statusCode = 200}) {
return Response(
statusCode,
body: message,
headers: {'Content-Type': 'text/plain'},
);
}
static Response fromError(IError error) {
// Print error to console
print('Error: ${error.code.name} - ${error.message}');
//print(error.stackTrace);
return Response(
mapErrorCodeToHttpStatus(error.code),
body: jsonEncode({
'code': error.code.name,
'error': error.message,
'details': error.details,
}),
headers: {'Content-Type': 'application/json'},
);
}
}
int mapErrorCodeToHttpStatus(ErrorCode errorCode) {
switch (errorCode) {
case ErrorCode.networkError:
return 503; // Service Unavailable
case ErrorCode.validationError:
case ErrorCode.inputError:
return 400; // Bad Request
case ErrorCode.unexpectedError:
case ErrorCode.internalError:
case ErrorCode.databaseError:
return 500; // Internal Server Error
case ErrorCode.authenticationError:
return 401; // Unauthorized
case ErrorCode.permissionDenied:
return 403; // Forbidden
case ErrorCode.notFound:
return 404; // Not Found
case ErrorCode.mappingError:
case ErrorCode.outputError:
return 422; // Unprocessable Entity
case ErrorCode.exception:
case ErrorCode.unknownError:
return 520; // Unknown Error (Custom)
default:
return 500; // Fallback: Internal Server Error
}
}