Catching Sql Exception In Entity Framework4?What is the best practice? - entity-framework

What practices do you use in your datalayer to catch sql exceptions?
Has anybody written a Generic Sql Exception handler where they catch the most common errors ?
how do you do it any examples out there?
Thanks

Handle unexpected exception by the underlying layer only
Exceptions from your data layer (in this case Entity Framework) should be handled only by your business layer. The business layer can raise then (if necessary) a more high-level exception for your presentation layer (UI).
Don't throw and catch exceptions across more than one layer of your application. This is considered to be bad practice. The presentation layer should only handle business layer exceptions.
Never swallow exceptions by using:
try {} catch (Exception) { // who cares }
Catch expected exceptions as early as possible
Always try to handle expected exceptions (e.g. FileNotFoundException) as soon as possible. If you can handle it, handle it directly there. If not, re-throw a Custom Exception and handle it in your underlying layer.
Don't clear the stack trace when re-throwing an exception
Catch and re-throw implicitly (see)
try {} catch (Exception) { throw; }
and not explicitly
try {} catch (Exception ex) { throw ex; }

Related

Autofac - (Global) Handler/Middleware to unwrap exceptions

We would like to add a handler/middleware to Autofac to essentially unwrap any Autofac.Core.DependencyResolutionException; to throw the inner exception.
Hooking the Activation (or RegistrationPipelineStart) Pipeline phases (using the following code) unwraps one of the exceptions, but the exception ultimately get wrapped by another DependencyResolutionException.
container.RegisterServiceMiddleware<IOController>(PipelinePhase.ResolveRequestStart, (context, next) =>
{
try
{
next(context);
}
catch (Exception ex)
{
// This unwraps one exception, but even if this is done another exception is wrapped.
// If the inner exception is not thrown, there is a DependencyResolutionException wrapped in another DependencyResolutionException
throw ex.InnerException;
}
});
Irrespective of the phase, I always end up with the exception being wrapped.
I think I need to override the behaviour of ActivatorErrorHandlingMiddleware, but I cannot see a way to do this.
(I understand that Constructors should be lightweight an not throw exceptions, but we have a very large application, and are in the process of refactoring the internals...this will take several versions/iterations, so not really a possibility).
Many Thanks in advance.

Throwing Exceptions in Dart for Invalid Parameters (e.g. Sign In)?

I have an async function signIn in a Dart program that takes username and password string arguments. The function calls a remote server and the server responds with a session token or validation messages in the case of missing or incorrect username and/or password.
Currently I have this implemented with callbacks. The appropriate callback is called after the server responds. No need for await.
signIn(username, password, onSuccess, onFailure);
The more I read about Dart, I feel like the above isn't really the Dart way of doing things. Should I be using await combined with try and catch? Something like the following?
try {
sessionToken = await signIn(username, password);
// navigate from the sign in screen to the home screen.
} on InvalidParams catch (e) {
// e contains the server's validation messages
// show them to the user.
}
Invalid sign in credentials are likely. Handling them is normal program flow. I was taught never to use try/catch for regular, expected program flow. It seems that the Dart language is encouraging using exception handling for this especially in combination with await.
From Error class documentation [Emphasis mine.]
If the conditions are not detectable before calling a function, the
called function should not throw an Error. It may still throw a value,
but the caller will have to catch the thrown value, effectively making
it an alternative result rather than an error. The thrown object can
choose to implement Exception to document that it represents an
exceptional, but not erroneous, occurrence, but it has no other effect
than documentation.
What's the best most Dart way to implement this?
Error vs. Exception
The documentation you linked essentially says that the Error class should not be used for what you define as "regular, expected program flow" but Exception should. This also means that using try-catch for addressing these kinds of cases is encouraged in Dart.
From the documentation, Error's should be used for "a program failure that the programmer should have avoided", i.e. unexpected program flow. However, Exception's are "intended to convey information to the user about a failure, so that the error can be addressed programmatically", i.e. expected program flow.
In order to implement exceptions, you will have to extend Exception and create your own exception class. Dart enforces this by not providing access to the message passed to a regular Exception.
Creating instances of Exception directly with new Exception("message") is discouraged, and only included as a temporary measure during development, until the actual exceptions used by a library are done.
Example
enum InvalidCredentials { username, password }
class InvalidCredentialsException implements Exception {
final InvalidCredentials message;
const InvalidCredentialsException({this.message});
}
function() {
try {
await signIn(username, password);
} on InvalidCredentialsException catch (e) {
switch (e.message) {
case InvalidCredential.username:
// Handle invalid username.
break;
case InvalidCredential.password:
// Handle invalid password.
break;
}
} on Error catch (e) {
print(e);
} catch (e) {
// Handle all other exceptions.
}
}
I created InvalidCredentialsException to handle invalid credentials passed to signIn. For the message (you can call it whatever you want), I simply used an enum to distinguish between an invalid username and an invalid password (probably not what you would want to do, it should just explain the concept).
When handling it using try-catch, you can create different catch-blocks for different types. In my example, I use on InvalidCredentialsException for responding to the expected exception in your program flow and another one on Error for unexpected failures.
When using on for catch-statements, you run the risk of not catching other types of exceptions, which will then be thrown. If you want to prevent that, you can either have another block for generic exceptions, i.e. on Exception or just have a generic catch-block at the end (catch (e)).
You might want to override toString in your exception class if you want to be able to print out your exception.
Additionally, you can obviously transport as much information with your exception as you like, e.g. (modified from the above code):
// ...
throw InvalidCredentialsException(cause: InvalidCredentials.password, message: password);
// ...
class InvalidCredentialsException implements Exception {
final InvalidCredentials cause;
final String message;
const InvalidCredentialsException({this.cause, this.message});
}

Should functions that return Future[A] throw exceptions?

I have come across functions that return Future but also throw exceptions immediately. For example like this:
def func(): Future[String] {
if (something) {
// this
Future.failed(new RuntimeException("test"))
} else {
// and this
throw new RuntimeException("test")
}
}
This behaviour seems annoying for the caller, because you have to do something like this to catch both errors:
try {
func() recover {
case e: Exception => handleError(e)
}
} catch {
case e: Exception => Future.successful(handleError(e)) //or Future.failed etc
}
I have noticed that the WSClient in play framework does this (both throwing exceptions if the URL is malformed, and returning a Future which fails if the HTTP request fails).
Is this good practice? Is there a better way to handle errors from functions that behave like this?
Future is used to return something eventually, but its not clear when this actually happens.
Coming from a .NET perspective (we have Task): an exception should be thrown if the request is clearly invalid (such as an malformed url). You already know this before actually making the web request, so there is no need in delaying the exceptions.
On the other hand, if the server is down (timeout?) or the server returns something your client doesn't understand: this can and must be handled at a later time, since the response is not directly available when making the call. We would be able to block until the response is available, but that would render the Future useless.
I think this is best compared with the 'Exit early' programming style.

Entity framework context in using block

I am writing a service layer application, which interacts with database using Entity framework.
I am enclosing my individual "unit-of-work" in a using block, where I initialise my data context.
However I need to throw some exceptions, to convey database errors to applications, which are using my service application. So I am doing something like this:
using (dbcontext = new DbContext())
{
throw new Exception("Error while Saving data");
}
Can anyone confirm if this is Ok? Will Entity framework data context be disposed off correctly even after an exception is thrown?
Yes. A using block is converted to a try/finally block when compiling with disposing logic inside the finally block.
However your exception will not be thrown outside if the Dispose method throws an exception.
Yes this is correct. From MSDN:
A using statement can be exited either when the end of the using
statement is reached or if an exception is thrown and control leaves
the statement block before the end of the statement.
That being said, I would throw a more specific exception than the Exception one.

Do Action Helpers with hooks to auto-run, throw exceptions or not?

UPDATED
Wanting some code to run with each controller, and being told to use Action Helpers or a Plugin rather than extending from a Base Controller, I decided on an Action Helper rather than Plugin, per excellent slides by #Bittarman (Ryan Mauger);
Zend Framework, getting to grips:
http://www.slideshare.net/rmauger/zend-framework-getting-to-grips
See slide 22:
Thrown Exceptions in (action helpers) Pre/Post Dispatch will stop further execution...
While it DOES stop further execution, the exception wasn't caught. I've been trying to debug this for hours but not getting anywhere.
If you run the following code, are you seeing exceptions caught or is it escaping the Error Controller?
I'm trying to figure out whether Zend Framework is NOT behaving as expected, or if I totally messed something up (more likely).
I tried to break this down into the simplest case to replicate, let me know what you see:
/* add to existing Bootstrap located here: APPLICATION_PATH/Bootstrap.php */
protected function _initActionHelpers()
{
Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH .'/controllers/helpers');
//hooks cause action helper to autorun: http://akrabat.com/zend-framework/hooks-in-action-helpers/
$hooks = Zend_Controller_Action_HelperBroker::getStaticHelper('Test');
Zend_Controller_Action_HelperBroker::addHelper($hooks);
}
/* in: APPLICATION_PATH/controllers/helpers/Test.php */
<?php
class Zend_Controller_Action_Helper_Test extends Zend_Controller_Action_Helper_Abstract
{
public function preDispatch()
{
// you can skip next line if you don't have xdebug
//xdebug_disable();
throw new Exception('test', 404);
parent::preDispatch();
}
}
Update:
OK, I've been running this through xDebug + Eclipse... (it was either that or have fun poking my eyes out, not sure if I chose the more pleasurable experience)....and I found out something bizarre.
The preDispatch is running twice!
And on the second call, it goes to the Zend_Controller_Plugin/ErrorHandler.php
where it runs this code:
if ($this->_isInsideErrorHandlerLoop) {
$exceptions = $response->getException();
if (count($exceptions) > $this->_exceptionCountAtFirstEncounter) {
// Exception thrown by error handler; tell the front controller to throw it
$frontController->throwExceptions(true);
throw array_pop($exceptions);
}
}
By setting throw Exceptions to true, it no longer gets caught. And I suspect this is to save a loop from occurring ($this->_isInsideErrorHandlerLoop is a subtle clue too ;)
Why is it in a loop?
OK, #Bittarman gave me the answer in #ZFTalk on IRC. Here it is (and apologies that I will mark my own answer as correct..but I don't want to bug him even more to write it up here).
if( ($this->getRequest()->getActionName() == 'error') && ($this->getRequest()->getControllerName() == 'error')) {
return;
}
The reason for this is that the error handler has to disable itself
(by setting throw exceptions to true) when its in the error
handler loop. So you have
to make sure your exception condition does not occur in the error controller.
The ErrorHandler plugin is designed to catch exceptions thrown by the mvc-component, not by plugins. It hooks into the postDispatch and checks for exceptions of the dispatch - and nothing else.
It won't catch exceptions prior to this like in the preDispatch.
If you have a look at the source of the ErrorHandler Plugin you can see that it checks for Exceptions in the Request object. This only works if the frontController option 'throwExceptions' is set to false which makes him to catch exceptions and store them for later use (like the plugin handler).
In your case the exception isn't caught by the frontcontroller thus thrown to the very top of the application. You sure can edit the frontController to catch exceptions prior to the dispatch - but this isn't implemented intentional: everything prior to the dispatch can be seen as "booting" the application: any exception there is critical. Like in real booting, any exception there stops the application to run. So you really should avoid any exceptions there.
Update: Ok this was for the plugin part and forgot you wanted to know for the ActionHelper part. Those aren't executed by the FrontController but by the Zend_Controller_Action. As there they're part of the dispatching and caught by the FrontController and handled by the ErrorHandler plugin.
But what does the ErrorHandler do? It adds another request to the FrontController with your errorController. So another dispatching loop is done and again, your actionhelper does throws an exception. As the errorController request isn't different to any other request, the ErrorHandler plugin would catch it again and chain another request of the errorController. Which again.. i guess you can see where this would lead to - a loop. To prevent this there is a property to see if there was already an exception somewhere. This is to catch any exception thrown by the error handler. If the ErrorHandler plugin notices such an exception it overwrites the throwException property to true and throws the exception.
So the unhandled exception you can see is the exception which rises from the errorController request.
I can see the point that ActionHelpers can throw an exception - but you should be really careful with that for exactly this reason ;)