I am using the firebase auth now I want to show a different message in UI for every error message
You have to check for specific error messages in your catch block and add custom handling.
You don't mention the language you're working in (and I'm not familiar with all of the different libraries), but C# will throw a FirebaseAuthException containing the property AuthErrorCode which is an enum representing the error. You could check that in, say, a switch statement to get the required message.
try {
userRecord = await _FirebaseAuth.GetUserByEmailAsync(email, token)
.ConfigureAwait(false);
}
catch (FirebaseAuthException ex) {
if (ex.AuthErrorCode == AuthErrorCode.UserNotFound) {
DisplayError($"Error retrieving user record for {email}");
}
}
Related
I have a web api which I call from my angularjs application. I have a method where (if all is OK) I return a list of strings. But if something goes wrong and I catch an exception, how should I handle this?
I'm quite new to this and I'm wondering how I should do about error handling? Are there any best practices for what return type I should use in a case like this?
1.
[HttpGet]
[Route("{user}")]
public IHttpActionResult GetItems(string user)
{
try
{
return Ok(adObject.GetItems(user)); //List of strings
}
catch (Exception e)
{
//return e how? Or log error? Both?
throw;
}
}
2.
[HttpGet]
[Route("{user}")]
public List<string> GetItems(string user)
{
return adObject.GetItems(user);
}
You should return a 500 http status code with enough information to tell the UI that an error occurred without revealing the inner workings of the API. For instance, you might say "unable to insert a new record". If the error is a result of the UI sending bad data, you would instead send a 400 series status code such as a 422.
To do all of this, there are two options. You can simply send back an InternalServerError like this:
[HttpGet]
[Route("{user}")]
public IHttpActionResult GetItems(string user)
{
try
{
return Ok(adObject.GetItems(user)); //List of strings
}
catch (Exception e)
{
Return InternalServerError();
LogError(e);
}
}
Which will just return a 500 error and log the the exception (you would need to write the LogError method).
You could also call ResponseMessage instead of InternalServerError and return your own HttpResponseMessage with more detail on the problem. Both of these methods are on the ApiController if you want to investigate their signatures or see others that you might be able to use.
The other option is to create a custom exception filter that inherits from ExceptionHandler. A good example of how to do this is available on this website:
http://www.brytheitguy.com/?p=29
Hope that helps.
I read somewhere that TRY CATCH is not recommended in Web API methods.
I'm making the following call into a method and if all goes well, I want to return an Employee object along with Status 200 but if something goes wrong e.g. database call fails, etc. I want to return status 500. What's the right way to handle that code?
[HttpPost]
public async Task<IHttpActionResult> PostNewEmployeeAsync(Employee emp)
{
var newEmployee = await RegisterEmployee(emp);
return Ok(emp);
// What if I had a database error in RegisterEmployee method. How do I detect the error and send InternalServerError()
}
private async Task<Employee> RegisterEmployee(Employee emp)
{
// Call DB to register new employee, then return Employee object
}
Your code should return the error code that matches the case that you have, for example if your code couldn't find the required resource in the database return NotFound,
but if you code raises an exception, avoid wrapping your code by try/catch block and instead the exception should bubble up to the level that you can handle it globally, to do this you have many options like :
1- Implement an ExceptionFilter where you can handle all the unhandled exceptions raised in your controllers (this doesn't include any exception happens before the controllers in the pipeline).
See this for more details about ExceptionFilterAttribute.
2- If you are using Web API 2, you can implement the interface IExceptionHandler where you can handle all the exception happens anywhere in the pipeline and there you can return the errors you want.
See this for more details about Global Exception Handling in Web API 2.
Hope that helps.
You don't want to avoid try/catch entirely, you just need to be really careful about it. Wrap your code in a try block, and catch the exception you're expecting. Inside the catch, return the error response.
I am developing simple chat application using CWE which sends messages by using contextual data. I'm having "Specified method is not supported" exception message. This exception occurs when I try to start chat with group. one-to-one chat works fine with no exception. since I'm having same code on both sender & receiver side, I'm confused that how to make this work. Please help.
My code snippet as as follows.
void method1()
{
//
//here I have code to send an IM saying "lets chat in extension window"
//
try
{
Dictionary<ContextType, object> context = new Dictionary<ContextType, object>();
context.Add(ContextType.ApplicationId, "{1226271D-64C9-4F24-B416-E6A583F45A1C}");
context.Add(ContextType.ApplicationData, "initial_data_request");
try { IAsyncResult res = conversation.BeginSendInitialContext(context, null, null); }
catch (Exception e1)
{
MessageBox.Show(e1.Data+"\n\n"+e1.Message);
}
}
catch (Exception ee)
{
MessageBox.Show("Client Platform Exception: " + ee.Message);
}
}
This is the method I call when my application starts. It is supposed to send initial context so that receiver clients when receive this should open my extension application.
I found the answer. It is showing that exception because contextual data will not work in a group conversation.
Found the related thread here..
http://social.msdn.microsoft.com/Forums/lync/en-US/b4e46648-7097-4348-8327-6864f1c12ab2/contextdata-in-a-group-conversation?forum=communicatorsdk
I've seen a number of posts and articles but am not able to see the solution crisply.
I've installed Elmah.MVC via NuGet and have commented out this line from FilterConfig.cs:
//filters.Add(new HandleErrorAttribute());
So that Elmah would pick up the errors.
It works when I provide an invalid action name and I get a yellow page as well as an email.
I want to know about two other types of errors that my code may generate... how are we supposed to handle them:
1.E.g. if my repository or manager (business logic) layer throws an exception when trying to access database or send an email etc.
a. Is the correct way to NOT implement any kind of try catch in Controllers (or anywhere else for that matter) and let Elmah take care of exceptions?
b. If so, and if it shows a yellow error page, how can we show a view of our own liking?
2.If my view contains ajax calls, e.g. via jqgrid, and behind the scenes there are errors, I've noticed they also get picked up properly by Elmah. But how do I show some kind of an error message to the user as well?
Thanks
Here is what I did:
In controller, I placed try catch:
try
{
//model = getmodelfromdb();
return View("MyView", model);
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return View("../Error/ShowException", ex);
}
For custom view for 404, I did this in global.asax:
protected void Application_OnError( )
{
var exception = Server.GetLastError( );
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
Helper.SetSessionValue(SessionKeys.EXCEPTION, exception);
Response.Redirect( "~/Error/ShowException");
}
For jqgrid, I did this in my controller:
[HttpPost]
public ActionResult ListRecords( int page , DateTime? fromdate , DateTime? todate)
{
try
{
var list = FetchListFromDB();
var result = new
{
total = Math.Ceiling(list.Count / (decimal)Helper.PAGE_SIZE),
page = page, //--- current page
records = list.Count, //--- total items
rows = list.List.Select(x => new
{
id = x.EntityID,
cell = new string[]
{
x.Property1,
x.Property2
}
}).ToArray()
};
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
var result = new
{
errorMessage = "An unexpected error occurred while fetching data. An automatic email has been generated for the support team who will address this issue shortly. Details: " + ex.Message,
records = 0
};
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return Json(result, JsonRequestBehavior.AllowGet);
}
And this in the View (in the jqgrid definition):
loadComplete:function(data)
{
if (data.errorMessage)
{
alert(data.errorMessage);
}
},
In a general ajax scenario:
success: function(data)
{
if (data.errorMessage)
{
alert(data.errorMessage);
}
else
{
//...
}
},
a. Is the correct way to NOT implement any kind of try catch in Controllers (or anywhere else for that matter) and let Elmah take care of exceptions?
I'd say that Elmah doesn't "take care" of exceptions, it records them. Ideally, you should try to handle the errors - by all means log them, but also add logic to deal with them so that they don't interrupt the user's workflow.
I'd wrap logic in try blocks, and in the catch use
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
to record anything that goes wrong. Immediately after that line, however, I'd then do something to try to recover from the exception - catch specific exception types, never just catch (Exception e), and deal with them after logging them. The idea is that you should be reviewing your logs, working out what's causing the exceptions, and improving your program so that it doesn't throw exceptions any more.
To show your own error pages, there's the HandleErrorAttribute, or if you don't want to use that there's also the controller's OnException() method, which is called when a controller action method quits with an exception rather than finishing normally. An ExceptionContext object is passed into that method, so you can use that to get the exception that was thrown and log it, do any cleanup that might be required etc.
I know i'm very late to the party but I stumbled upon this answer while searching something similar form Google.
I don't like using try catch blocks everywhere in my code, especially in web apps. I let Elmah catch everything and log it behind the scenes. Then in the web.config file you can redirect based on the error type...
<customErrors mode="RemoteOnly" defaultRedirect="~/Error" >
<error statusCode="500" redirect="~/Error"/>
<error statusCode="404" redirect="~/NotFound"/>
</customErrors>
I am currently developing a Windows Phone 7 App that calls a WCF web service which I also control. The service offers an operation that returns the current user's account information when given a user's login name and password:
[ServiceContract]
public interface IWindowsPhoneService
{
[OperationContract]
[FaultContract(typeof(AuthenticationFault))]
WsAccountInfo GetAccountInfo(string iamLogin, string password);
}
Of course, there is always the possibility of an authentication failure and I want to convey that information to the WP7 app. I could simply return null in that case, but I would like to convey the reason why the authentication failed (i.e. login unknown, wrong password, account blocked, ...).
This is my implementation of the above operation (for testing purposes, all it does is throwing an exception):
public WsAccountInfo GetAccountInfo(string iamLogin, string password)
{
AuthenticationFault fault = new AuthenticationFault();
throw new FaultException<AuthenticationFault>(fault);
}
Now, if I call this operation in my WP7 app, like this:
Global.Proxy.GetAccountInfoCompleted += new EventHandler<RemoteService.GetAccountInfoCompletedEventArgs>(Proxy_GetAccountInfoCompleted);
Global.Proxy.GetAccountInfoAsync(txbLogin.Text, txbPassword.Password);
void Proxy_GetAccountInfoCompleted(object sender, RemoteService.GetAccountInfoCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
return;
}
}
The debugger breaks in Reference.cs, saying that FaultException'1 was unhandled, here:
public PhoneApp.RemoteService.WsAccountInfo EndGetAccountInfo(System.IAsyncResult result) {
object[] _args = new object[0];
PhoneApp.RemoteService.WsAccountInfo _result = ((PhoneApp.RemoteService.WsAccountInfo)(base.EndInvoke("GetAccountInfo", _args, result)));
return _result;
}
BEGIN UPDATE 1
When pressing F5, the exception bubbles to:
public PhoneApp.RemoteService.WsAccountInfo Result {
get {
base.RaiseExceptionIfNecessary(); // <-- here
return ((PhoneApp.RemoteService.WsAccountInfo)(this.results[0]));
}
}
and then to:
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
After that, the app terminates (with or without the debugger).
END UPDATE 1
Now, I would love to catch the exception in my code, but I am never given the chance, since my Completed handler is never reached.
Based on similar questions on this site, I have already tried the following:
Re-add the service reference --> no change
Re-create a really simple WCF service from scratch --> same problem
Start the app without the debugger to keep the app from breaking into the debugger --> well, it doesn't break, but the exception is not caught either, the app simply exits
Tell VS 2010 not to break on FaultExceptions (Debug > Options) --> does not have any effect
wrap every line in my app in try { ... } catch (FaultException) {} or even catch (Exception) --> never called.
BEGIN UPDATE 2
What I actually would like to achieve is one of the following:
ideally, reach GetAccountInfoCompleted(...) and be able to retrieve the exception via the GetAccountInfoCompletedEventArgs.Error property, or
be able to catch the exception via a try/catch clause
END UPDATE 2
I would be grateful for any advice that would help me resolve this issue.
The framework seems to read your WsAccountInfo.Result property.
This rethrows the exception on client side.
But you should be the first to read this property.
I don't know your AuthenticationFault class, does it have a DataContractAttribute and is it a known type like the example in
http://msdn.microsoft.com/en-us/library/system.servicemodel.faultcontractattribute.aspx ?
I believe I had the same problem. I resolved it by extending the proxy class and calling the private Begin.../End... methods within the Client object rather than using the public auto-generated methods on the Client object.
For more details, please see:
http://cbailiss.wordpress.com/2014/02/09/wcf-on-windows-phone-unable-to-catch-faultexception/