Flutter Http Exception has Occured. _Exception (Exception: Failed Load Data) - flutter

I want check if Api Url Statuscode is 200 , everything is ok untill in else statement .
I Got this error
Exception has occurred.
_Exception (Exception: Failed Load Data)
It's My Code Api
Future<List<Mosque>> getMahasiswaById(String id) async {
var baseURL=Urls.BASE_API_URL;
var apiRespon = await http.get('$baseURL/mahasiswa/get/id/$id');
if(apiRespon.statusCode == 200) {
final apiResponJson = json.decode(apiRespon.body);
print(apiResponJson);
return (apiResponJson['data'] as List).map((p)=>Mosque.fromJson(p)).toList();
} else {
throw Exception('Failed Load Data');
}
}
How can i fix this ? Thanks

always use try and catch with http requests it'll help you to identify the source of the exception , you can do something like that :
Future<List<Mosque>> getMahasiswaById(String id) async{
var baseURL=Urls.BASE_API_URL;
try{
var apiRespon = await http.get('$baseURL/mahasiswa/get/id/$id');
if(apiRespon.statusCode == 200){
final apiResponJson = json.decode(apiRespon.body);
print(apiResponJson);
return (apiResponJson['data'] as List).map((p)=>Mosque.fromJson(p)).toList();
}
else {
print(apiReson.statusCode.toString());
throw Exception('Failed load data with status code ${apiReson.statusCode}');
}
catch(e){
print (e);
throw e;}
}
most of the time the exceptions come from bad internet connection , issue in the back end or lost in the internet connection ,when you use the above code it'll print out the type of the exception so you can identify the root of the error.
I hope that can help

Related

flutter dart Try/Catch not working properly

While learning flutter/dart, I came across this issue:
I'm calling this method in a FutureBuilder somewhere in my app:
Future<DatabaseUser> getOrCreateUser({required String email}) async {
try {
final user = await getUser(email: email);
return user;
} on UserDoesNotExistsException {
final createdUser = await createUser(email: email);
return createdUser;
} catch (e) {
print(e);
rethrow;
}
}
Once called for the first time, the "getUser" throws a UserDoesNotExistsException, which is correct, so it should go to the line:
} on UserDoesNotExistsException {
This is the issue, it always goes straight to the line:
} catch (e) {
If I print (e), I have UserDoesNotExistsException (see screenshot)
Let me know if you need more context here, what could make sense in that situation? Why is the Exception not caught by the right bloc?
Any help would be really appreciated
PS: I'm following this 37h+ video tutorial: https://www.youtube.com/watch?v=VPvVD8t02U8&t=28781s I'm at 21:36:00
Thanks
Screenshot Debugger
Issue solved.
As julemand101 suggested, a print(e.runtimeType) exposed the type of e as Type and not Exception.
The reason was a missing () when the Exception is thrown:
if (result.isEmpty) {
throw UserDoesNotExistsException;
} else {
return DatabaseUser.fromRow(result.first);
}
instead of
if (result.isEmpty) {
throw UserDoesNotExistsException();
} else {
return DatabaseUser.fromRow(result.first);
}
Visual Studio Code doesn't give any warning about this by default, but as julemand101 suggested in the comments, the analyzer can be configured to give a warning when you don't throw an Error or Exception:
https://dart-lang.github.io/linter/lints/only_throw_errors.html

How to merge aqueduct Future<RequestOrResponse> with dart console app?

Thanks to Bryan from voidrealms. I was struggling last 2 days (and weeks of resarch) and now I can get big data using dart tcp socket from the old system very fast. The process with dart console app is much faster than the dart Future project.
Now problem to mixing dart console app to aqueduct Future app. In below I put my questions after (********).
If I use Socket.connect("192..... Inside Future the process will be very slow and sometimes returns null response. So, my question is how to merge aqueduct Future with dart console app.
aqueduct.io part
class NtmsApiController extends Controller {
#override
Future<RequestOrResponse> handle(Request request) async {
try {
if (request.path.remainingPath != null) {
_requestValue = request.path.remainingPath;
// (********) In here I need to add below code, how?
}
} else {
_secureResponse = "$_errorData";
}
} catch (e) {
_secureResponse = "$_errorData";
}
return new Response.ok("$_secureResponse")
..contentType = ContentType.json;
}
}
dart console app
import 'dart:io';
import 'dart:async';
Socket socket;
String _response;
String _requestedData;
Stopwatch _stopWatch;
void main() {
_stopWatch = Stopwatch()..start();
_response = "";
_requestedData = "Q77:_:NBRT:_:6785417534\r\n";
Socket.connect("192.168.22.120", 3000).then((Socket sock) {
socket = sock;
socket.write('$_requestedData\r\n');
socket.listen(dataHandler,
onError: errorHandler,
onDone: doneHandler,
cancelOnError: false);
}).catchError((AsyncError e) {
print("Unable to connect: $e");
});
print("_requestedData: $_requestedData");
}
void dataHandler(data){
_response = new String.fromCharCodes(data).trim();
_printResponse(_response);
}
void errorHandler(error, StackTrace trace){
print(error);
}
void doneHandler(){
socket.destroy();
}
void _printResponse(String _response) {
// approximately I get 500 rows with 20 column data in 250ms
print("$_response ... (${_stopWatch.elapsedMilliseconds} ms)");
_stopWatch..stop();
if(_stopWatch.isRunning == false) {
socket.close();
// (********)return response object to aqueduct Future request_response--- how?
}
}

Transaction already exists error

I'm using EF Core and Devart's data provider library. I've hit an issue I can't figure out with handling user input errors smoothly. The error seems to be limited to adding a new entity to the context.
Scenario
User inputs an invalid value in a field.
Save changes is called and throws then displays error.
Prompt user to fix the error.
After this if the error is fixed and save is called again (this is good data now), I get an exception "Transaction already exists" from the Devart data provider library.
StackTrace
at Devart.Data.Oracle.OracleConnection.BeginTransaction(IsolationLevel il)
at Devart.Data.Oracle.OracleConnection.BeginDbTransaction(IsolationLevel isolationLevel)
at System.Data.Common.DbConnection.BeginTransaction(IsolationLevel isolationLevel)
at  .BeginDbTransaction(IsolationLevel )
at System.Data.Common.DbConnection.BeginTransaction(IsolationLevel isolationLevel)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.BeginTransactionWithNoPreconditions(IsolationLevel isolationLevel)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.BeginTransaction(IsolationLevel isolationLevel)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.BeginTransaction()
at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.BeginTransaction()
at
I tried to break out the transaction and handle it manually MSDN Transactions but I still get the same error.
public bool SaveAllChanges()
{
var result = false;
using (var transaction = _context.Database.BeginTransaction())
{
try
{
_context.Database.AutoTransactionsEnabled = false;
_context.SaveChanges(true);
transaction.Commit();
result = true;
}
catch (Exception exc)
{
InvokeError(exc, "Error saving changes.");
result = false;
}
}
_context.Database.AutoTransactionsEnabled = true;
_context.Database.CloseConnection();
return result;
}
How do I recover from a db error without scrapping all of the user's input? I would hate for that to be practice. I could be validating all the data going in but recovering from simple errors would be better.
After fussing around with this I found the magic sauce. This type of error only seems to come up when adding an object to the DB. It's as if the context doesn't dispose of the transaction on fail.
public bool SaveAllChanges()
{
var result = false;
_context.Database.AutoTransactionsEnabled = false;
using (var transaction = _context.Database.BeginTransaction())
{
try
{
_context.SaveChanges(true);
transaction.Commit();
result = true;
}
catch (Exception exc)
{
transaction.Rollback(); <-------- Here.
InvokeError(exc, "Error saving changes.");
result = false;
}
}
_context.Database.AutoTransactionsEnabled = true;
_context.Database.CloseConnection();
return result;
}
If someone has a solution to where I don't need to handle the transaction in this way please post it.
We cannot reproduce the "Transaction already exists" exception with the following code:
using (var _context = new MyContext())
{
var entity = new MyEntity() { ID = 10, Name = "entry exceeds max length of the field" };
_context.MyEntities.Add(entity);
try
{
_context.SaveChanges(true); // error
}
catch (Exception ex)
{
//InvokeError(exc, "Error saving changes.");
}
entity.Name = "correct input";
_context.SaveChanges(); // success
}
Please localize the issue in a small application and send us this project for reproducing.

Azure Mobile Apps Offline Client Throws NotSupportedException on Query

I have a Azure Mobile Apps Xamarin.Forms PCL client and have Offline Sync enabled. I tried to Pull data from my backend and afterwards query data from the offline storage with a Where clause. That throws the following exception and I don't know why.
Sync error: 'fahrerinfo.Imei.Equals("02032032030232")' is not supported in a 'Where' Mobile Services query expression.
public async Task SyncAsync()
{
ReadOnlyCollection<MobileServiceTableOperationError> syncErrors = null;
try
{
await OfflineSyncStoreManager.Instance.TruckFahrerTable.PullAsync("allTruckFahrerItems",
OfflineSyncStoreManager.Instance.TruckFahrerTable.CreateQuery());
Debug.WriteLine("SyncAsync: PUSH/PULL completed.");
}
catch (MobileServicePushFailedException e)
{
Debug.WriteLine("SyncAsync: PUSH failed.");
Debug.WriteLine(e.Message);
}
catch (Exception e)
{
Debug.WriteLine("SyncAsync: PUSH/PULL failed.");
Debug.WriteLine(e.Message);
//Debugger.Break();
}
}
public async Task<ObservableCollection<TruckFahrer>> GetTruckFaherAsync(bool syncItems)
{
try
{
if (syncItems)
{
await OfflineSyncStoreManager.Instance.SyncAsync().ConfigureAwait(false);
}
var deviceInfo = DependencyService.Get<IDeviceInfo>().GetPhoneInfo();
var imeiString = deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.ImeiKey];
var imei = imeiString.Equals("000000000000000") ? deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.IdKey] : imeiString;
IEnumerable<TruckFahrer> items =
await OfflineSyncStoreManager.Instance.TruckFahrerTable
//.Where(fahrerinfo => fahrerinfo.Imei.Equals(imei)) TODO: Why does that throw an exception???
.ToEnumerableAsync();
// TODO: Because above does not work
items = items.Where(fahrer => fahrer.Imei.Equals(imei));
return new ObservableCollection<TruckFahrer>(items);
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"Invalid sync operation: {0}", msioe.Message);
Debugger.Break();
}
catch (Exception e)
{
Debug.WriteLine(#"Sync error: {0}", e.Message);
Debugger.Break();
}
return null;
}
Thanks for any hint,
Eric
Are you a Java developer too? I'm and had this issue because in Java we need to compare strings with String#equals method, haha.
For some reason MobileServices doesn't allow us to use Equals in this situation.
To fix your problem, use == instead. As you can see here C# difference between == and Equals() both have the same effect in this case.
Where(fahrerinfo => fahrerinfo.Imei == imei)

HttpWebRequest maintenance and http web errors causing it to return "HRESULT E_FAIL" and "server not found"

I am iterating through a large list of objects (1503) and calling a save method on a ServiceProxy I have written. The service proxy uses the new networking stack in Silverlight 4 to call BeginGetRequestStream to start the process of asynchronously sending my objects to an azure REST service I have written for saving off the objects. The Http method I am using is POST. I know HttpWebClient is smart enough to reuse the Http connection so I am not concurrently opening 1503 connections to the server. Saving works fine and all 1503 objects are saved very quickly. However, when I try to save the same objects again, I expect to recieve an HttpStatus code of forbidden because the objects already exist and that is the code I set my azure web service to return. On small groups of objects, it works as expected. However, when I try saving the entire list of 1503 objects, I receive only 455 correct responses and 1048 errors such as "server not found" and
System.Exception ---> System.Exception:Error HRESULT E_FAIL has been returned from a call to a COM component.
at
System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)...
I wonder if there is some sort of book keeping or maintenance I am supposed to be performing on my HttpWebClient instances that I am neglecting and that is what is causing the http errors to throw exceptions but the new saves to work perfectly. Here is my code for handling the error cases:
private static void SendAncestorResponseCallback(IAsyncResult result)
{
var info = (SendAncestorInfo)result.AsyncState;
try
{
var response = info.Request.EndGetResponse(result);
info.Response = response;
}
catch ( Exception ex)
{
info.Error = ex;
}
info.MainThreadContext.Post(SendAncestorMainThreadCallback, info);
}
private static void SendAncestorMainThreadCallback(object state)
{
var info = (SendAncestorInfo)state;
IAncestor origAncestor = info.Content;
HttpWebResponse response = null;
if (info.Error != null)
{
if ((info.Error as WebException) == null)
{
info.Callback(false, origAncestor, null, info.Error);
return;
}
else //get response from WebException
{
response = (HttpWebResponse)(info.Error as WebException).Response;
}
}
else //get response from info.Response
{
response = info.Response as HttpWebResponse;
}
if (response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.Forbidden)
{
var stream = response.GetResponseStream();
using (var reader = new StreamReader(stream))
{
IAncestor retAncestor = XMLSerializerHelper.DeserializeObject<Ancestor>(reader.ReadToEnd());
info.Callback(response.StatusCode == HttpStatusCode.Created, origAncestor, retAncestor, null);
}
}
else info.Callback(false, origAncestor, null, info.Error);
}
considering how the web service is written I should only expect http status codes of created or forbidden and like I said with small groups this is the case. The fact that I only start getting the errors mentioned earlier makes me feel like I am doing something wrong with the HttpWebRequest objects etc. Any assistance would be greatly appreciated. Thanks.
--update here is the code that generates the HttpWebRequest:
foreach (IAncestor ancestor in ancestors)
{
AncestorViewModel ancestorVM = new AncestorViewModel(ancestor);
ancestorVM.Status = SaveStatus.Undefined;
ParsedAncestors.Add(ancestorVM);
_service.CreateAncestor(UserSrc, ancestor, (success, origAncestor, retAncestor, exception) =>
{
AncestorViewModel result = ParsedAncestors.First(a => a.Model.IdNo == origAncestor.IdNo);
if (exception == null)//web response was either Created or Forbidden
{
if (success)//Ancestor successfully created
{
savedAncestors++;
SuccessMessage = string.Format("{0} Saved\n", savedAncestors);
result.Status = SaveStatus.Saved;
}
else //Ancestor already existed
{
conflictAncestors.Add(origAncestor, retAncestor);
ConflictMessage = string.Format("{0} Conflicts\n", conflictAncestors.Count);
result.Status = SaveStatus.Conflicted;
}
}
else //Show exception recieved from remote web service
{
//if (exception as WebException != null)
//{
// //if exception is WebException get status code and description
// HttpWebResponse rs = (HttpWebResponse)(exception as WebException).Response;
// Message += string.Format("WebServer returned status code {0}: '{1}'\n", (int)rs.StatusCode, rs.StatusDescription);
//}
errors.Add(origAncestor, exception);
ErrorMessage = string.Format("{0} Errors\n", errors.Count);
result.Status = SaveStatus.Error;
}
});
}
public void CreateAncestor(string userSrc, IAncestor ancestor, Action<bool, IAncestor, IAncestor, Exception> callback)
{
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
var request = (HttpWebRequest)WebRequest.Create(
new Uri(string.Format("{0}/{1}/{2}", rootUri, AncestorsRestPoint, userSrc)));
request.Method = "POST";
request.ContentType = "application/xml";
var info = new SendAncestorInfo
{
Request = request,
Callback = callback,
Content = ancestor,
MainThreadContext = SynchronizationContext.Current
};
request.BeginGetRequestStream(SendAncestorRequestCallback, info);
}