Exception Handling in classes and Code Behind with C# - asp.net

I'm a little bit stuck with a asp.net project that i'm doing! I have got a class that is called from the code behind and many of its function have no return type ie, being void. How does one do exception handling then??? Also, if the function within the class does have a return type of, for instance, a dataset how would one then return an exception or indicate that an exception had occured? I have attached the following code from my class which is referenced from the code behind.
public void fnRecord(string []varList, string fnName)
{
try
{
String x;
StringBuilder SQLParameters = new StringBuilder();
SQLParameters.AppendLine("SELECT #{Function}(");
{
SQLParameters.Replace("#{Function}", fnName);
}
for (int i = 0; i < varList.Length; i++)
{
x = varList[i].ToString();
SQLParameters.Append("'" + x + "',");
}
SQLParameters.Remove((SQLParameters.Length - 1), 1);
SQLParameters.Append(")");
string SQLCMD = SQLParameters.ToString();
conn.Open();
NpgsqlCommand command = new NpgsqlCommand(SQLCMD, conn);
Object result = command.ExecuteScalar();
}
catch (NpgsqlException ne)
{
//return ne;
}
catch (Exception x)
{
//error code
}
finally
{
conn.Close();
}
}
Any help would be appreciated!
Thanks

Only catch the exceptions where you intend to handle them properly. If you want to reflect the errors in the UI, catch them at the UI. If you want to handle them and try to deal with the issue in the business logic, then catch them and handle them at that point.
By the way, your code is susceptable to SQL injection attacks. Best go learn something about parameterised queries.

You don't return exceptions. You throw them. That's the point of exceptions - you don't want exception handling cluttering your method signatures!
In your catch clauses, you don't actually do anything to handle the exceptions. Then you should not catch them at all, just let them bubble up to your code-behind, and catch them there - put a try-catch round the method call.
Alternatively, catch your SQL exceptions in your method, then throw a new exception with some sensible message, adding the SqlExceptions as the inner exception, like this
catch (NpgsqlException ne)
{
throw new Exception("Your explanatory message here", ne);
}
finally
{
...
}

Cool thanks for the answers... working with the obout library so have to try and work out their exception handling functions too.

Related

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast

hey Hi so this my service layer code
BillType billType=billTypeList.get(i);
This is my dao code:
#Override
public List<BillType> getBillTypeList(BillCategory billCategoryId){
Session session = null;
List<BillType> billTypeList=null;
try {
session=sessionFactory.openSession();
String sql = "select * from BILL_TYPE where BILL_CATEGORY_ID=:billCategoryId";
Query query = session.createSQLQuery(sql);
query.setParameter("billCategoryId", billCategoryId);
billTypeList= query.list();
}
catch(Exception e)
{
e.printStackTrace();
logger.error("Error in Method getBillType "+e.getMessage());
}
finally {
if (session != null) {
if (session.isOpen())
session.close();
}
}
return billTypeList;
}
This is the error i am getting:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.mppmcl.nonpower.model.BillType
Please tell me what to do. would be of great help. thanks in advance
Just to get rid of this error, by putting #SuppressWarnings on your method will do the trick.
But you should see a proper way to handle this here
Can you show us the attributes of BillType?Also there's an error in your code
query.setParameter("billCategoryId", billCategoryId);
You cant pass an Object as hibernate parameter. This will cause an unmatching type error. Try passing Integer values, it will match the ID Type.
Try this
query.setParameter("billCategoryId", billCategoryId.getId());
To know more about mapping, check this Java type Mappings

How to handle Internal server error (500) on spring rest API to custom the message?

I am working on spring rest api and I would like to sure everything is working fine. I would like to log abnormal behaviors database connection error among others, I'm working with couchbase database and I'm getting in the endpoint response for example for this kind of exception: CouchbaseQueryExecutionException the next message: Unable to execute query due to the following n1ql errors: \n{\"msg\":\"No index available on keyspace kids_club that matches your query. Use CREATE INDEX or CREATE PRIMARY INDEX to create an index, or check that your expected index is online.\",\"code\":4000} and a very long trace.
For this i found a solution on internet that is extend ResponseEntityExceptionHandler and override handleExceptionInternal method like this:
#ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
private static String DEFAULT_VALIDATION_ERROR_CODE = "KC-0020";
#ExceptionHandler(MiddlewareException.class)
protected ResponseEntity<ResponseBody> handleKidsClubException(MiddlewareException ex) {
return buildErrorResponse(HttpStatus.valueOf(ex.getHttpStatus()), ex.toError());
}
#ExceptionHandler(ServiceUnavailableException.class)
protected ResponseEntity<ResponseBody> handleServiceUnavailable(ServiceUnavailableException ex) {
return buildErrorResponse(INTERNAL_SERVER_ERROR, ex);
}
#ExceptionHandler(NoSuchElementException.class)
protected ResponseEntity<ResponseBody> handleNoFoundElement(NoSuchElementException ex) {
return buildErrorResponse(NOT_FOUND, ex);
}
#ExceptionHandler(CouchbaseQueryExecutionException.class)
protected ResponseEntity<ResponseBody> handleCouchbaseQueryException(ConstraintViolationException ex) {
return buildErrorResponse(BAD_REQUEST, ex);
}
}
But I'm not able to catch any kind of Internal Server Error in this way.
It seems like spring is handle and building the final message to the user.
Any ideas to resolve this?
Thanks.
#ExceptionHandler(NullPointerException.class)
public final ResponseEntity<Object> handleNullPointerException(NullPointerException ex, WebRequest request) {
LOGGER.info("Entering into the handleAllException method");
System.out.println("Exception is : " + ex.getClass());
ResponseData error = new ResponseData();
error.setRespCode(HttpStatus.NOT_FOUND.toString());
error.setRespMessage(ex.getLocalizedMessage());
error.setTimestamp(LocalDateTime.now());
return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
please try this way below to check whether you are able to catch exception or not.. From the sysout you will get the exact exception. Then you can use that exception to catch any particular exception from that business logic..

using vavr how to catch and re-throw the same exception

I am new to the functional style of programming using vavr.
I have a method returns the data when its executed successfully and if it fails, it returns the MyCustomRunTimeException.
In my Service class, I am calling this API method, when API method fails I have to catch the exception and going to clear my application cache and return the same exception to the caller (another service method in my case).
if method call success I have to return the actual object, not the Try wrapped object.
How can I achieve this using vavr Try?
I tried to use different methods in vavr Try.recover but I am unable to throw the same exception.
Any sample example or snippet could be very helpful for me if some can provide.
Thanks in advance.
Example:
Foo doFoo() {
throw new MyCustomRunTimeException();
}
method1(){
try{
doFoo();
}catch(MyCustomRunTimeException ex){
clearcache();
throw ex;
}
}
Basically, if your function throws, you want to do something (in case of failure) then throw it again?
How about this?
Foo doFoo() {
throw new MyCustomRunTimeException();
}
Foo myService() {
return Try.of(() -> doFoo())
.onFailure(e -> clearCache())
.getOrElseThrow(identity());
}
If I may: since you want to try functional style, we usually don't rely on exceptions in FP, instead we rely on types that represent possibility of failure, like Either<MyBusinessProblem, Foo>.
Then your code would look like:
Either<MyBusinessProblem, Foo> doFoo() {
return Left.of(new MyBusinessProblem());
}
Either<MyBusinessProblem, Foo> doFoo() myService() {
return doFoo()
.peekLeft(businessProblem -> clearCache());
}
As a bonus, now your code is explicit and you don't risk forgetting handling an error.

Ignore ThreadAbortException when logging exceptions

What's the correct way of ignoring ThreadAbortException when logging exceptions?
Is it safe to just catch it in an empty catch block to make it disappear?
If you need to stop a ThreadAbortException propogating further up the call stack, you can call Thread.ResetAbort. So try something like:
try
{
// some code
}
catch (ThreadAbortException ex)
{
// do some logging
Thread.ResetAbort();
}
As for "correct" - that depends on your usage scenario. I'd generally be cautious about catching these unless you understand exactly why it has been raised. In escence it is a "stop now, quickly, and drop what you are doing" signal. Resetting it and going on to do further processing should be done with caution.
Employ two catch blocks: one for ThreadAbortException and one for the rest, for example:
void MainLoop()
{ bool workdone;
try
{ while( IsWorking ) // cross-thread volatile variable
{ workdone = Process();
if( !workdone )
{ Thread.Sleep( 500 ); }
}
}
catch( ThreadAbortException )
{ // Forced termination. Exit silently.
}
catch (Exception e)
{ LogError( e ); }
}
It is safe to catch it in a separate catch block. As an alternative you can catch all Exceptions and then check if a given Exception e is ThreadAbortException
I leave this post just because of the comments. Obviously, I was not knowing much about that exception.
With newer .NET versions ignoring an exception can be simplified to
try
{ // ...
}
catch (Exception e) when (!(e is ThreadAbortException))
{ LogError( e );
}
But this might still not be enough. Some libraries tend to wrap all exceptions with their own exception. In this case it could happen that the ThreadAbortExceptiononly appears as InnerException. I would not call it best practice to wrap a ThreadAbortException but it is real world.
To come around this I recommend an extension:
public static bool IsThreadAbort(this Exception ex)
{
while (ex != null)
{
if (ex is ThreadAbortException)
return true;
ex = ex.InnerException;
}
return false;
}
Now you can check with:
catch (Exception e) when (!e.IsThreadAbort())
{ LogError( e );
}

Visual Studio ignore try catch - debug only

I think error handling is a good idea. :) When debugging it can get in the way - especially with nice user friendly messages. In VB6 I could just check a box for the compiler to ignore my error handling. I found the dialog that allows me to do something similar in VS, but it's about 10,000 check boxes instead of one - which is too many to change every time I want a production compilation.
Is there a way to set VS up so when I am in debugging mode I get one set of conditions and when I am in production I get another? ...or is there just another method to handling errors and debugging more efficiently?
Thanks
Try the Debug Menu and look at Exceptions. You can set it to automatically break when an exception is thrown.
In code, I'd probably just do something like:
#if !DEBUG
try {
#endif
DoSomething();
#if !DEBUG
} catch (Exception ex) {
LogEx(ex);
throw new FriendlyException(ex);
}
#endif
Or. more generally and with less #if:
#if DEBUG
public const bool DEBUG = true;
#else
public const bool DEBUG = false;
#endif
try {
DoSomething();
} catch (Exception ex) {
if (DEBUG) throw;
LogEx(ex);
throw new FriendlyException(ex);
}
Or, general purpose (like the Exception Handling library from P&P):
bool HandleException(Exception ex) {
return !DEBUG;
}
But, if your real problem is just the Visual Studio GUI - just use a macro.
You can add this attribute to your methods:
[Conditional("DEBUG")]
You can also use #if #endif statements if you wish.

Resources