Display string from raise_application_error in java program - sql

I am raising some application errors from PL/SQL procedures. I am setting some messages for instance,
RAISE_APPLICATION_ERROR(-20001, 'message');
Is there any way, I can display 'message' in exception section in catch block of java program from which I called this procedure?

If you're doing catch (Exception e), message should be available from e.getMessage().
If you're doing catch (SQLException e) (or whatever the exception type is for your data access package) message should still be available from e.getMessage(). Additionally, the -20001 should come through in e.getErrorCode(). Note that it may come through as the absolute value (20001 as opposed to -20001); you'll have to experiment.

I think this post will help you out: Error catching
catch (GenericJdbcException ge) {
IF (se.getErrorCode() == -20001)
If your not using Hibernate you might need to change the error type.

Related

Should i print error message in logs or inside exception or both?

I have this code in Scala:
logger.error("Repository does not exists or does not contains 'definitions' directory")
throw new FileNotFoundException("Repository does not exists or does not contains 'definitions' directory")
Should i write message twice? Or should i only log the error and throw empty exception?
It depends, use cases to use cases.
If your log statement is within dev-scope then there is no need to throw exception to the source/caller. you can log exception and silent it and return back useful message/code to source/caller.

How to catch an exception thrown by JIRA SOAP in VB.NET?

I want to catch the exceptions thrown by the login() function in JIRA's SOAP API. The function login throws 2 exceptions. RemoteAuthenticationException if the user provided an invalid username or password and RemoteException if there was some problem preventing the operation from working.
Currently I'm using this code to catch the exception
Try
...
Catch jiraException As Exception
MsgBox(jiraException.toString)
End Try
I entered an invalid username and password and printed the exception. It says something like this:
System.ServiceMode.FaultException: com.atlassian.jira.rpc.exception.RemoteAuthenticationException: Invalid username or password.
I want to catch the two exceptions separately. How can I do this? Thanks in advance!
You should be able to catch these as FaultException Of com.atlassian.jira.rpc.exception.RemoteAuthenticationException and FaultException Of com.atlassian.jira.rpc.exception.RemoteException.

How to catch error while inserting data with SqlDataSource

I have a SqlDataSource and a GridView.
What I want to do is, while the query is executed (i.e. for inserting a data), then after the data has inserted successfully, it should appear a message sounds: "The data deleted successfully". I've solved it by using GridView1_RowDeleted method.
Now the problem is, I want to catch the error while the query is failed to executed. If the query has failed to execute, then it should appear a message: "The data failed to insert.".
How to do it? I don't have an idea about this.
Need your help guys.
Thanks a lot.
You should be able to add a handler for the relevant event: inserted, deleted. Then, in the handler look at the SqlDataSourceStatusEventArgs property Exception. If it's not null then an
exception has occurred. For example if the selected command threw an
exception:
protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
// handle the exception
}
}
--

WCF throwing CommunicationException when FaultException is thrown

Solution:
A bit of tracing showed the CommunicationException was being thrown because there was an issue with my exception T not serializing correctly; because, two layers deep, I had an anonymously typed object, which was unserializable. Removing it and bubbling up the changes appeared to fix it. There was somethinge else small I did before that, but I can't remember for the life of me what it was, only that it wasn't done in the config.
I was getting messages from my traces such as:
Type 'RebuiltWCFService.Requests.HelloWorldRequest' with data contract name 'HelloWorldRequest:http://schemas.datacontract.org/2004/07/RebuiltWCFService.Requests' is not expected.
Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
Original post
I've encountered a seemingly strange issue today that I just cant't find an answer to!
The problem: my service is throwing a CommunicationException when I throw a FaultException! It does not do this if I don't throw an exception.
In my service, I'm properly defining the fault contracts:
[OperationContract]
[FaultContract(typeof(Faults.HelloWorldFault))]
Responses.HelloWorldResponse HelloWorld(Requests.HelloWorldRequest parameter);
Then under error conditions I'm throwing an exception of the correct type:
if (_errors.Count() > 0)
{
Faults.HelloWorldFault fault = new Faults.HelloWorldFault(_errors);
throw new FaultException<Faults.HelloWorldFault>(fault, new FaultReason("There are one or more errors in the request. Check the 'Errors' property for more detaisl"));
}
And then I'm catching it on the client end:
try
{
response = client.HelloWorld(new BasicService.HelloWorldRequest() { Number = 49 });
client.Close();
Console.WriteLine(String.Format("Response message: {0}, Response number: {1}", response.Message, response.Number));
}
catch (FaultException<BasicService.HelloWorldFault> ex)
{
...
}
That all seems OK to me, and like it should work. However, as soon as I go to test my error clauses (by providing bad data, such as a missing field), the whole thing dies on me. When I throw my FaultException, the service instead throws a CommunicationException with the message
An error occurred while receiving the HTTP response to http://localhost:8732/Design_Time_Addresses/RebuiltWCFService/Service1/.
This could be due to the service endpoint binding not using the HTTP protocol.
This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down).
See server logs for more details.
Can anybody offer some insight on this one? I am using the basicHttp binding, and I've also tried it with wsHttp. I will post my config file upon request.
A FaultException is a child of CommunicationException. So there is nothing wrong in what's happening in your code.
If you are uncertain about what the exception is while handling, it is usually reported as CommunicationException. If you want to handle your specific exception in your own way, use the following structure.
try
{ ... }
catch (FaultException<MyDemoException> me)
{ ... }
catch (FaultException fe)
{ ... }
catch (CommunicationException ce)
{ ... }
catch (Exception ex)
{ ... }
In the above structure, Exception is parent of CommunicationException. CommunicationException is the parent of FaultException and so on.
System.Object
System.Exception
System.SystemException
System.ServiceModel.CommunicationException
System.ServiceModel.FaultException
System.ServiceModel.FaultException<TDetail>
System.ServiceModel.Web.WebFaultException<T>
Thanks guys, you helped me to understand the issue in a better way. My observation: I kept a List MyData - to hold any generic/dynamic collection, that was unable to serialize, so resulting to close the connection, so the communication exception.
When I removed the List from Fault Contract, and throw Fault style, it was clearly giving Fault contract exception, instead of communication exception.
Hope it helps,
HydTechie.
I ran into this problem because I had one or more breakpoints in the wrong place. I removed all breakpoints with Debug..Delete all Breakpoints (Ctrl-Alt-F9), and all of the CommunicationException exceptions disappeared and were replaced with the correct messages coming back.
Yes, the timeout is 60 seconds, so this never should have occurred, so it was probably some weird artifact of Visual Studio 2012.

SQL Try catch purpose unclear

Let's suppose I want to inform the application about what happened / returned the SQL server. Let's have this code block:
BEGIN TRY
-- Generate divide-by-zero error.
SELECT 1/0;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() as ErrorState,
ERROR_PROCEDURE() as ErrorProcedure,
ERROR_LINE() as ErrorLine,
ERROR_MESSAGE() as ErrorMessage;
END CATCH;
GO
and Let's have this code block:
SELECT 1/0;
My question is:
Both return the division by zero error. What I don't understand clearly is that why I should surround it with the try catch clausule when I got that error in both cases ?
Isn't it true that this error will be in both cases propagated to the client application ?
Yes, the only reason for a Try Catch, (as in ordinary code) is if you can "Handle" the error, i.e., you can correct for the error and successfully complete whatever function the procedure was tasked to do, or, if want to do something with the error before returning it to the client (like modify the message, or store it in an error log table or send someone an email, etc. (althought i'd prefer to do most of those things from the DAL layer )
Technically, however, the catch clause is not returning an error. it is just returning a resultset with error information. This is very different, as it will not cause an exception in client code. This is why your conclusion is correct, ou should just let the original error propagate directly back to the client code.
As you have written it, no error will be returned to the client. As in ordinary code, if you do not handle (correct for) the error in a catch clause, you should always rethrow it (in sql that means Raiserror function) in a catch clause. What you have done above, in general is bad, the client code may or may not have any capability to properly deal with
a completely different recordset (one with error info) from what it was expecting. Some calls (like Inserts updates or deletes) may not be expecting or looking for a returned recordset at all... Instead, if you want or need to do something with the error in the procedure before returning it to the client, use Raiserror() function
BEGIN TRY
-- Generate divide-by-zero error.
SELECT 1/0;
END TRY
BEGIN CATCH
-- Other code to do logging, whatever ...
Raiserror(ERROR_MESSAGE(), ERROR_NUMBER(), ERROR_STATE() )
END CATCH;
Both return the division by zero
error.
Yes, but using different return paths.
The difference is that in the first example, you are anticipating the error and dealing with it in some way. The error enters the application as a regular result - it is not propagated via the error handling mechanism. In fact, if the application doesn't look specifically as the shape of the result, then it may be unaware that an error has occurred.
In the second instance, the error will propagate to your application typically via an error reporting mechanism, such as an exception. This will abort the operation. How big an impact this has will depend upon the application's exception handling. Maybe it will abort just the current operation, or the entire app may fail, depending upon the app's design and tolerance to exceptions.
You choose what makes sense for your application. Can the app meaningfully handle the error - if so, propagate the error (2nd example), or is it best handled in the query (1st example), with errors being "smoothed over" by returning default results, such as an empty rowset.
Try Catch is not as useful when all you have in the try portion is a select. However if you have a transaction with multiple steps, the catch block is used to roll all the steps back and possibly to record details about what caused the problem in a log. But the most important part is the rollback to ensure data integrity.
If you are creating dynamic SQl within the Try block, it is also helpful to log the dynamic SQl variable that failed and any parameters passed in. This can help resolve some hard-to-catch, "we don't have any idea what the user actually did to cause the problem" errors.
No, by executing Select 1/0 in a TRY/CATCH block the select statement returns nothing and the select statement in the catch block displays the error details gracefully. The query completes successfully - no errors are thrown.
If you run Select 1/0 on it's own the query does not complete successfully - it bombs out with an error.
Using a catch block within SQL gives you the chance to do something about it there and then not just let the error bubble up to the application.
The only reason you see the error details is because you are selecting them. If there was no code within the Catch block you wouldn't see any error information.
Using the first method, you wont get the error from SQL Server directly
The second method may stop the execution of the statements that follow it
So it is better you catch it in advance