Error Handling in WCF Service - wcf

With the following service method example:-
[PrincipalPermission(SecurityAction.Demand, Role="BUILTIN\\Administrator")]
public string GetTest()
{
try
{
return "Hello";
}
catch (Exception ex)
{
throw ex;
}
}
How do I get an error from the method when the caller is not in the correct Role. In design time the error breaks on the method line (i.e. public string GetTest) and does not reach the catch. At run time it is reported in my silverlight application as an unhandled error (I have try.. catch blocks there too).
There doesn't seem to be a place to catch the error as it never gets into the try blocks!!

The check for the role is made (by the WCF runtime) before the method is actually called - not inside the method!
You need to handle this exception on the caller's side when you make this call.
If you need to check certain conditions inside your service code, don't decorate the method with an attribute, but instead use the role provider in code to check for a given condition.

If you want global error handler for your WCF service you can implement IErrorHandler and add it in custom behavior. Operation can't catch exceptions thrown outside of its try block.

Related

Proper way to send Web API response

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.

How to catch exception with action composition in Play 2.3.X

I'm developing an application using Play 2.3.1.
I'm annotating all my controllers with the following Action :
#Override
public Promise<Result> call(final Context ctx) throws Throwable {
try {
return delegate.call(ctx);
} catch (MyCustomException e) {
return handleCustomException(e);
} catch (Exception e) {
return handleUnexpectedError(e);
}
}
The aim of this action is to catch any exception thrown by a controller method in order to send a clean message to the user.
MyCustomException is my application specific exception that extends Exception.
The problem is that even if I throw a MyCustomException in the method of my controller, the corresponding catch statement is never executed.
I always have a RuntimeException caused by my MyCustomException.
The consequence is that no matter what exception occured, the user always sees the result sent by handleUnexpectedError(e).
What am I doing wrong ? Thanks.
After some investigation, the guilty is the Security action of Play.
More details here : https://groups.google.com/forum/#!topic/play-framework/AY4NuQziYyM
Because I added my custom actions at AbstractController level and the #Authenticated(Authenticator.class) annotation at the controller level, the security action composition is the last one to be executed.
Because of the Security.java at line 51, even if my exception is expected, Play throws a RuntimeException.
So the solution is to add the security annotation at method level in order to be sure that it is executed before the first execution of the method.

WP7: Unable to catch FaultException in asynchronous calls to WCF service

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/

Serializing Linq2Sql over Wcf - bug or misunderstanding?

Working with Linq2Sql as a driver for a Wcf Service. Lets go bottom up....
Down at the bottom, we have the method that hits Linq2Sql...
public virtual void UpdateCmsDealer(CmsDealer currentCmsDealer)
{
this.Context.CmsDealers.Attach(currentCmsDealer,
this.ChangeSet.GetOriginal(currentCmsDealer));
}
That gets used by my Wcf service as such...
public bool UpdateDealer(CmsDealer dealer)
{
try
{
domainservice.UpdateCmsDealer(dealer);
return true;
}
catch
{
return false;
}
}
And called from my Wpf client code thus (pseudocode below)...
[...pull the coreDealer object from Wcf, it is a CmsDealer...]
[...update the coreDealer object with new data, not touchign the relation fields...]
try
{
contextCore.UpdateDealer(coreDealer);
}
catch (Exception ex)
{
[...handle the error...]
}
Now, the CmsDealer type has >1< foriegn key relationship, it uses a "StateId" field to link to a CmsItemStates table. So yes, in the above coreDealer.StateId is filled, and I can access data on coreDealer.CmsItemState.Title does show me the tile of the appropriate state.
Now, here is the thing... if you comment out the line...
domainservice.UpdateCmsDealer(dealer);
In the Wcf service it STILL bombs with the exception below, which indicates to me that it isn't really a Linq2Sql problem but rather a Linq2Sql over Wcf issue.
"System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException was unhandled by user code
Message="Operation is not valid due to the current state of the object."
InnerException is NULL. The end result of it all when it bubles up to the error handler (the Catch ex bloc) the exception message will complain about the deserializer. When I can snatch a debug, the actual code throwing the error is this snippit from the CmsDealer model code built by Linq2Sql.
[Column(Storage="_StateId", DbType="UniqueIdentifier NOT NULL")]
public System.Guid StateId
{
get
{
return this._StateId;
}
set
{
if ((this._StateId != value))
{
if (this._CmsItemState.HasLoadedOrAssignedValue)
{
throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();
}
this.OnStateIdChanging(value);
this.SendPropertyChanging();
this._StateId = value;
this.SendPropertyChanged("StateId");
this.OnStateIdChanged();
}
}
}
In short, it would appear that some stuff is happening "under the covers" which is fine but the documentation is nonexistent. Hell googleing for "ForeignKeyReferenceAlreadyHasValueException" turns up almost nothing :)
I would prefer to continue working with the Linq2Sql objects directly over Wcf. I could, if needed, create a flat proxy class that had no association, ship it up the wire to Wcf then use it as a data source for a server side update... but that seems like a lot of effort when clearly this is an intended scenario... right?
Thanks!
The default serializer will first set the State, which will set the StateId. After that it will try to set the serialized StateId and then the exception is thrown.
The problem is that you did not specify that you want you classes to be decorated with the DataContract attribute.
Go to the properties of your LinqToSqlGenerator and set the Serialization Mode to Unidirectional
This will cause the tool to add the DataMember attribute to the required properties and you will see that the StateId will not be a DataMember since it will be automatically set when the State Property is set while deserializing.
The error is likely due to something changing the fk value after it has been initially set - are you sure you don't have some custom initialisation code somewhere that might be initially setting the value?
You could breakpoint the set (where it's throwing), and step out each time it's set (skipping the exception if you need to) which should hopefully point you in the right direction.

When is the last moment I can return an exception to a client in WCF?

Let's say I have this in an implementation of IInstanceProvider:
public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
try
{
unitOfWork.Commit();
}
catch (Exception)
{
unitOfWork.Rollback();
throw;
}
finally
{
unitOfWork.Dispose();
}
}
That throw; will never be returned to the client because it is being called after the service has done it's work and returned data to the client, and is therefore done. How else can I return the exception? Or is there a better place to do this?
I think you are looking in the wrong place to do this. I think a better choice would be to implement the IDispatchMessageInspector interface and attach it to the collection exposed by the MessageInspectors property on the DispatchRuntime (through a behavior, most likely).
With this, you can inspect messages coming in and going out, and modify them if need be (which is how your exception would be realized, as a fault in the return message). Because of this, you will not just let the exception bubble up, but rather, you would change it to a fault message and set the return message to that.
I'm not as familiar with transactions in WCF as I should be. What in the above code returns the results to the client? Is it the rollback?