I am trying to save my Error Message and StackTrace when my Xamarin.Android App crashes.
In Xamarin.iOS I can simply wrap my Main-Method in a Try-Catch-Block as you can see in the screenshot below:
Since there is no Main-Method in Xamarin.Android (just my MainLauncher Activity), I ask myself the question, if there is a similarly simple method to log the exceptions.
I found a solution to Log all Unhandled Exception:
In my MainLauncher Activity:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
AndroidEnvironment.UnhandledExceptionRaiser += HandleAndroidException;
and
private void HandleAndroidException(object sender, RaiseThrowableEventArgs e)
{
e.Handled = true;
Logger = new LogUtils();
Logger.Log("ERROR: Unhandled Exception");
Logger.Log("MESSAGE: " + e.Exception.Message);
Logger.Log("STACKTRACE: " + e.Exception.StackTrace);
}
Related
I'm new in reactive programming using project reactor, I don't understand why I can't execute the method doOnError() in this case :
public class MyTest{
public static void main(String[] args) {
getMonoWithError().doOnError(throwable ->System.out.println(" " + throwable)).subscribe();}
private Mono<String> getMonoWithError() {throw new RuntimeException("MONO IN ERROR.....");}
}
Thank you for your help.
I expect to print the message "Error while processing....." and get the exception in the console.
I have a custom handler like this:
Public class DatabaseAuthenticationHandler extends AbstractJdbcUsernamePasswordAuthenticationHandler {
#Override
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(
UsernamePasswordCredential credential, String originalPassword) throws GeneralSecurityException, PreventedException {
final String username = credential.getUsername();
logger.debug("***Username:"+username);
logger.debug("***Password:"+credential.getPassword());
return createHandlerResult(credential, new SimplePrincipal(), null);
}
#Override
public boolean supports(final Credential credential) {
return true;
}
}
To me, this should always log a user in no matter what. But I see in the logs this:
ERROR [org.apereo.cas.authentication.PolicyBasedAuthenticationManager]
- <Authentication has failed. Credentials may be incorrect or CAS cannot find authentication handler that supports
[UsernamePasswordCredential(username=sadf, source=MyJDBCAuthenticationManager)] of type [UsernamePasswordCredential].
Examine the configuration to ensure a method of authentication is defined and analyze CAS logs at DEBUG level to trace the authentication event.
which makes no sense to me as I can see in the logs that cas is calling the authenticatUsernamePasswordInternal method. Obviously this handler supports, well everything.
Why can't I log in?
I think you best use principalFactory.createPrincipal to create the principal rather than returning an new SimplePrincipal().
In your AuthenticationEventExecutionPlanConfigurer & DatabaseAuthenticationHandler, add the following:
AuthenticationEventExecutionPlanConfigurer.java
#Autowired
#Qualifier("principalFactory")
private PrincipalFactory principalFactory;
#Bean
public DatabaseAuthenticationHandler databaseAuthenticationHandler() {
return new DatabaseAuthenticationHandler(principalFactory);
}
DatabaseAuthenticationHandler
Public class DatabaseAuthenticationHandler extends AbstractJdbcUsernamePasswordAuthenticationHandler {
private final PrincipalFactory principalFactory;
public DatabaseAuthenticationHandler (PrincipalFactory principalFactory){
this.principalFactory = principalFactory;
}
#Override
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(
UsernamePasswordCredential credential, String originalPassword) throws GeneralSecurityException, PreventedException {
final String username = credential.getUsername();
logger.debug("***Username:"+username);
logger.debug("***Password:"+credential.getPassword());
/////// below here's the change /////////
return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null);
}
#Override
public boolean supports(final Credential credential) {
return true;
}
}
See if the above works, thanks.
The root cause of this problem is that you pass a null parameter to createHandlerResult method,you can change it to new ArrayList<>. I also encountered this problem(My CAS version is 5.3.9).And I also tried the solution gaving by Ng Sek Long,but it didn't work.Then I tried to solve it by myself. I searched for the error message in CAS code and found it in PolicyBasedAuthenticationManager class.
try {
PrincipalResolver resolver = this.getPrincipalResolverLinkedToHandlerIfAny(handler, transaction);
LOGGER.debug("Attempting authentication of [{}] using [{}]", credential.getId(), handler.getName());
this.authenticateAndResolvePrincipal(builder, credential, resolver, handler);
AuthenticationCredentialsThreadLocalBinder.bindInProgress(builder.build());
Pair<Boolean, Set<Throwable>> failures = this.evaluateAuthenticationPolicies(builder.build(), transaction);
proceedWithNextHandler = !(Boolean)failures.getKey();
} catch (Exception var15) {
LOGGER.error("Authentication has failed. Credentials may be incorrect or CAS cannot find authentication handler that supports [{}] of type [{}]. Examine the configuration to ensure a method of authentication is defined and analyze CAS logs at DEBUG level to trace the authentication event.", credential, credential.getClass().getSimpleName());
this.handleAuthenticationException(var15, handler.getName(), builder);
proceedWithNextHandler = true;
}
In the above code snippet, the authenticateAndResolvePrincipal method declaired two kinds of exception.Looked at this method, I found there is a line of code which may throws that two.
AuthenticationHandlerExecutionResult result = handler.authenticate(credential);
The key code which lead to this problem is in DefaultAuthenticationHandlerExecutionResult class.
public DefaultAuthenticationHandlerExecutionResult(final AuthenticationHandler source, final CredentialMetaData metaData, final Principal p, #NonNull final List<MessageDescriptor> warnings) {
this(StringUtils.isBlank(source.getName()) ? source.getClass().getSimpleName() : source.getName(), metaData, p, warnings);
if (warnings == null) {
throw new NullPointerException("warnings is marked #NonNull but is null");
}
}
So, if you use createHandlerResult(credential, new SimplePrincipal(), null), NullPointerException will throw at runtime.It will be catched by catch (Exception var15) code bock and log the error message you see.
During page navigatin within my app I display a message in the system tray to the user along with the progress bar to indicate something is going on.
The problem I'm having is during debug I am randomly getting the following error:
{System.NullReferenceException: Object reference not set to an instance of an object.
at ContosoSocial.SetProgressIndicator.<>c__DisplayClass1.<runSystrayMessage>b__0(Object sender, EventArgs args)
at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)} System.Exception {System.NullReferenceException}
Stacktrace:
StackTrace " at ContosoSocial.SetProgressIndicator.<>c__DisplayClass1.<runSystrayMessage>b__0(Object sender, EventArgs args)\r\n at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)\r\n at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)" string
I'm still new to VS2013 and Windows Phone programming so really need a little help here figuring out how to trace and fix this problem?
The error seems to be random, here is an example of the class displaying the system tray message and calling method:
class SetProgressIndicator
{
public void runSystrayMessage(bool isVisible, string text, int length)
{
try
{
SystemTray.ProgressIndicator = new ProgressIndicator();
SystemTray.ProgressIndicator.IsVisible = true;
SystemTray.ProgressIndicator.Text = text;
SystemTray.ProgressIndicator.IsIndeterminate = isVisible;
}
catch (System.InvalidOperationException e)
{
Debug.WriteLine("Exception caught in runSystrayMessage(): \r\n" + e);
}
DispatcherTimer timer = new DispatcherTimer();
try
{
timer.Interval = TimeSpan.FromMilliseconds(length);
}
catch(ArgumentOutOfRangeException e)
{
Debug.WriteLine("Exception caught in runSystrayMessage(): \r\n" + e);
}
timer.Tick += (sender, args) =>
{
try
{
SystemTray.ProgressIndicator.IsVisible = false;
}
catch(System.InvalidOperationException e)
{
Debug.WriteLine("Exception caught in runSystrayMessage(): \r\n" + e);
}
timer.Stop();
};
timer.Start();
}
}
}
Example of a calling method:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
SetProgressIndicator progInd = new SetProgressIndicator();
// Check for full licnece before removing ad's
if (TrialExperienceHelper.LicenseMode == TrialExperienceHelper.LicenseModes.Full)
{
GOTPubCenter10.Visibility = Visibility.Collapsed;
}
// Dispaly message in system tray
if (hasBeenVisited)
{
progInd.runSystrayMessage(true, "Entering house selection menu...", 2500);
}
else
{
progInd.runSystrayMessage(true, "Select house library to enter...", 8000);
hasBeenVisited = true;
}
}
Ideas and suggestions on how to solve the problem appreciated.
After doing some research online I found that this would be the way to catch the exceptions and output my own error messages. For some reason I still cannot seem to catch the errors. Below is the code for a class that overrides antlrs default error handling.
All I want to do is catch the exception from antlr and output to the screen that the syntax is incorrect in a java gui.
public class ExceptionErrorStrategy extends DefaultErrorStrategy {
#Override
public void recover(Parser recognizer, RecognitionException e) {
throw e;
}
#Override
public void reportInputMismatch(Parser recognizer, InputMismatchException e) throws RecognitionException {
String msg = "Input is mismatched " + getTokenErrorDisplay(e.getOffendingToken());
msg += " expecting: "+e.getExpectedTokens().toString(recognizer.getTokenNames());
RecognitionException ex = new RecognitionException(msg, recognizer, recognizer.getInputStream(), recognizer.getContext());
ex.initCause(e);
throw ex;
}
#Override
public void reportMissingToken(Parser recognizer) {
beginErrorCondition(recognizer);
Token t = recognizer.getCurrentToken();
IntervalSet expecting = getExpectedTokens(recognizer);
String msg = "Missing "+expecting.toString(recognizer.getTokenNames()) + " at " + getTokenErrorDisplay(t);
throw new RecognitionException(msg, recognizer, recognizer.getInputStream(), recognizer.getContext());
}
}
If all you want to do is report errors, then you are probably looking for the ANTLRErrorListener interface, not the AntlrErrorStrategy interface. The latter is geared towards actually modifying the behavior of the parser in response to errors, e.g. for automatic recovery attempts.
In ANTLRWorks 2, I use the following two classes as my primary implementations of this interface:
SyntaxErrorListener
DescriptiveErrorListener
I'm developing app which connects to service and consume some JSON data. Consuming works great (JSON.net rocks) but I wonder where I should catch exception error annd show simple MessageBox? Tried in few places but still my app is closing. Or maybe I should do it based on json response which contain error tag? I think that normal error handling could be easier, but have blank spot in my mind now..
Code is below:
private void LoginLoginButton_Click(object sender, System.EventArgs e)
{
((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;
ProgressOverlay.Show();
GenerateLoginString();
var w = new SharpGIS.GZipWebClient();
Observable.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
.Subscribe(r =>
{
var settings = IsolatedStorageSettings.ApplicationSettings;
var deserializedRootObject = JsonConvert.DeserializeObject<RootObject>(r.EventArgs.Result);
UserSettings us = new UserSettings()
{
first_name = deserializedRootObject.user.first_name,
last_name = deserializedRootObject.user.last_name,
user_id = deserializedRootObject.user_id,
};
settings.Add("UserSettings", us);
settings.Save();
});
w.DownloadStringAsync(new Uri(UserUri));
w.DownloadStringCompleted += new DownloadStringCompletedEventHandler(w_DownloadStringCompleted);
}
void w_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
If you mean you want to catch an exception which occurs in your web client call then it should be in the Error property of DownloadStringCompletedEventArgs.
void w_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if(e.Error != null)
{
MessageBox.Show("An error occurred!");
}
else
{
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
}
Solved!
I used try and catch in this case. Works perfect :)