I use for two providers for Entity Framework Core in my ASP.NET Core application. SqlServer for production mode and Sqlite for integration tests mode.
In my application DbContext, when an exception occurs during SaveChangesAsync, I catch it to know what kind of problem occurred. I do that to be able to detect unique index constraint violation for example.
I have the following problems: it seems that different exception types are created for Sqlite and SqlServer providers (SqlException and SqliteException). These exceptions have different ErrorCode so I have to always specify the two error codes if I want to detect one kind of error.
Did someone find any solution to easily manage usual relational database errors and to get the same exception handler work for many providers ?
More of that, do you have any solution to know what is the type of the entity throwing the exception or do we have to get it from the string Message included in the exception?
Thanks in advance for your answers
For SQL Server error codes, you can refer here: Database engine errors
For Sqlite error codes, you can refer here: Result and Error Codes
For getting the entity, you will not know that from SqlException. But you can catch more specific exceptions. For instance, DbUpdateConcurrencyException has an Entries property you can work with.
Reference: Resolving concurrency conflicts
Here is an example for an handling an auth error that might work for you:
try
{
⋮
}
catch (SqlException e)
{
foreach (SqlError sqlError in e.Errors)
{
switch (sqlError.Number)
{
case 10028:
{
HandleAuthError(e);
break;
}
⋮
}
}
}
catch (SqliteException e)
{
switch (e.SqliteErrorCode)
{
case 23:
{
HandleAuthError(e);
break;
}
⋮
}
}
private void HandleAuthError(SystemException e)
{
⋮
}
Note : In 3.0.1, a bug makes that Entries Collection is empty when a unique index constraint violation is raised... Supposed to be fixed in 3.1
Related
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}");
}
}
Me and my friend have some arguement about Exceptions. He proposes to use Exception as some kind of transporter for response (we can't just return it). I'm saying its contradictory to the OOP rules, he say it's ok because application flow was changed and information was passed.
Can you help us settle the dispute?
function example() {
result = pdo.find();
if (result) {
e = new UniqueException();
e.setExistingItem(result);
throw new e;
}
}
try {
this.example();
} catch (UniqueException e) {
this.response(e.getExistingItem());
}
Using exceptions for application flow is a misleading practice. Anyone else (even you) maintaining that code will be puzzled because the function of the exception in your flow is totally different to the semantic of exceptions.
I imagine the reason you're doing this is because you want to return different results. For that, create a new class Result, that holds all information and react to it via an if-statement.
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/
I have a class that handles all the interaction in my application with my WCF service and it seems that MSDN say that the use of Using)_ statement with WCF is bad - I can see why this is bad and agree with it (http://msdn.microsoft.com/en-us/library/aa355056.aspx)
my problem is that their suggested method of implementation will mean that i have 10 methods [as 10 public methods in my service] that will have the same structure code and this of course does not follow the DRY principal - the code looks similar to the following:
try
{
results = _client.MethodCall(input parameteres);
_client.Close();
}
catch (CommunicationException)
{
if (_client != null && _client.State != CommunicationState.Closed)
{
_client.Abort();
}
}
catch (TimeoutException)
{
if (_client != null && _client.State != CommunicationState.Closed)
{
_client.Abort();
}
}
catch (Exception ex)
{
if (_client != null && _client.State != CommunicationState.Closed)
{
_client.Abort();
}
throw;
}
This doesn't have any logging yet but of course when I do come to start logging it then I will have to add the logging work in almost 10 different places
does anyone have any tips on how I can be a bit more resourceful here in reusing code
thanks
paul
I would use some general-purpose, configurable exception handling component that allows basic exception handling processing like logging, re-throwing etc. to be decoupled from the actual place of handling. One example of such a component is Microsoft's Exception Handling Application Block.
Then you could end up with a code like this:
try
{
results = _client.MethodCall(input parameteres);
_client.Close();
}
catch (Exception ex)
{
_client.CloseIfNeeded();
if (!ex.Handle("Wcf.Policy")) throw;
}
where CloseIfNeeded denotes a custom extension method encapsulating the WCF channel closing logic, and the Handle exception method calls the exception handling mechanism, passing in a name of the exception policy that shall be applied on this place.
In most cases, you can reduce exception handling logic to a decent one or two lines of code, giving you several benefits:
instant configurability of exception handling behavior (policies)
extensibility with custom exception handlers bound to specific types of exceptions and exception policies
better manageability and readability of code