Does Spring override try catch in the controller class with the SimpleExceptionResolver - spring-mvc

I am planning to use SimpleExceptionResolver for handling most generic exceptions like unhandled runtime exceptions. e.g. NullPointerException, NumberFormatException etc. and wil redirect to common error jsp
However in the controller I would catch the application specific exceptions like custom exceptions.
My question is :
Lets say if SimpleExceptionResolver is configured to catch the Exception class, will it override the controller level catch stattements and catch all the excptions instead. My guess is, SimpleExceptionResolver does not give opportunity to the Controller class to handle any custom exception.
Kindly provide valuable suggestions and workarounds thnks

If you are using try catch(Exception e) block,in your controller,that means you are already handling the exception,inside your controller classes.It will not be handled by HandlerExceptionResolver class.Only those exception which can not be caught inside the controller are propagated to HandlerExceptionResolver.
I would suggest in case of exception in your controller classes,you can use try catch block,and from catch block you can throw your own custom exception,which will be propagated to SimpleMappingExceptionResolver,and there you can prepare response message as per the exception type and cause.

Related

Exception the exception thrown from Stream.forEach() in ControllerAdvice

In my Spring MVC Based application, I have a ControllerAdvice defined.
Now, in one of my service classes, I have this parallelStream created:
rawImportList.parallelStream().forEach(rawImportBatch -> {
rawImportBatch.parallelStream().forEach(this::importNominationFromRawImport)
});
The importNominationFromRawImport() method here, by definition, could throw a custom exception that should ideally be handled in the ControllerAdvice.
What could be the best way to achieve this?

Advice on exception handling in webservice

I need some advice on a good exception handling strategy in my webservice.
My web service methods are doing the standard CRUD operations against an Oracle database. Therefore, I have some methods that select data and return a dataset and others that do either an insert/update/ or delete and don't return anything.
Initially, I had all my code in each webservice method in a try-catch-finally catching an Oracle exception. I read some articles on the web that says this is not good and I should only surround something in try-catch if there is a potential for an exception. Now I am thinking that maybe it would be best if I put only my Insert/Update/Delete methods in try-catch-finally blocks.
So my questions are:
Should I put all my methods in try-catch-finally? They all interact with Oracle and could potentially cause an exception. Or should I only do this for the Insert/Update and Delete methods?
I don't really have any requirements on what they want to happen when an exception does occur. I am just going on common sense. I know that they definitely don't want the app to end. I am planning on logging the exception in some manner and re-throwing it to the client. I am doing this when there is an Oracle Exception.
Basically you need to do try-catch on every WebMethod. Since the event won't bubble up, I think there is no other better way.
However, you can use the trick in this post to make your life easier.
The way he does is creating a utility method like this and invoke that method by passing it a delegate to your web method logic.
private T Execute<T>(Func<T> body)
{
//wrap everything in common try/catch
try
{
return body();
}
catch (SoapException)
{
//rethrow any pre-generated SOAP faults
throw;
}
catch (ValidationException ex)
{
//validation error caused by client
ClientError innerError = new ClientError();
//TODO: populate client error as needed
//throw SOAP fault
throw this.GenerateSoapException(
"An error occurred while validating the client request.",
SoapException.ClientFaultCode,
innerError);
}
catch (Exception ex)
{
//everything else is treated as an error caused by server
ServerError innerError = new ServerError();
//TODO: populate server error as needed
//TODO: log error
//throw SOAP fault
throw this.GenerateSoapException(
"An unexpected error occurred on the server.",
SoapException.ServerFaultCode,
innerError);
}
}
I assume you are using ASP.NET WebMethods. My advice is that you always catch exceptions on the service layer, write a log and throw a SoapException. Basically you can try-catch on each service method (WebMethod). If you fail to do so, you would be exposing exception details to the client calling the service and that could be a potential security issue.

Spring MVC: global exception handler

I want to implement some kind of global event handler but only for error logging purpose and without any redirection.
For example, the controller's method fails and my event handler will catch the exception (of any kind or specific type of exception) and does some logic and that's it. After that the controller's logic will continue. I checked the ExceptionHandler but it requires to return Model/Map or handle the response so it doesn't help me.
Is it possible?
Thank you
Have you ever considered AOP for your requirement ? Use - After Throwing Advice.

Is it possible to write a base class to handle nullReferenceException from all pages?

I am using .net framework 4.0, plain asp.net and working with webform. Currently I having a base class to handle all parameter passing and redirect. I wonder is it possible to write a base class to handle nullRefeerenceException from all pages in once, lets say redirect end user to somewhere or display particular error message.
Scenario: For example, some pages must come along with parameter, if no parameter captured, I would like to redirect them to somewhere.
You can try to control the ProcessRequest. You need to test it to see if can do the work you ask for, but this is a good point to capture all errors of your page.
public override void ProcessRequest(HttpContext context)
{
try
{
base.ProcessRequest(context);
}
catch (Exception x)
{
// handle here your error from the page...
}
}
Some more notes
I was use this code on one critical page, but I do not use it for all my page. Even tho can capture the errors, some times you can not do nothing else here other than throw again the final error, so end up that is better to log your unknown and unhandled errors from globa.asax Application_Error, and on page make sure that you use try/catch to handle them where they happens.
After some think maybe is not good practice to use it. Good practice is to use try/catch in the place that you may have throws and not a general one like that.
Last
You also get throw error here when the user close the connection before the end of the render, but if you log the errors you get the same on Application_Error - this is not a page error.
Exception of type 'System.Web.HttpUnhandledException' was thrown. --->
System.Web.HttpException: The remote host closed the connection.
The error code is 0x80072746.
In you Global.asax, handle Application_Error.
When a NullReferenceException is handled by the server a 500 response is created. Redirect all of your server 500 messages however you want. This guide will help.
Definitive Guide to Handling 500 Errors in IIS6, IIS7, ASP.NET MVC3 with Custom Page
You can hook up to every uncatched NullReference Exception, depending on what you want to do.
For instance you can use the global.asax, to be specific the Application_Error Event. You can get a reference to the exception, look for the type and perform a redirect there.
Another way to get ahold of exceptions would be to write your custom error provider, but that wouldn't give you the possibility to perform a redirect.

Wrapping a web service in try/catch block

Is it best practice to wrap a web service method/call into a try/catch block?
I don't web service requests tend to be the reason why the .NET desktop applications crash? So I was thinking all calls should be wrapped in try/catch to prevent this.
Good idea?
Also, should it throw an exception or just have an empty catch?
I am assuming you are using WCF, since your question is tagged with it. A good practice in exception handling with WFC is not allowing exceptions to bubble across the wire to your consumer, but throw meaningful FaultExceptions instead.
You should always have a try...catch block in your operation if there is any chance an exception could be generated by it. If you allow the raw excption to bubble, only two scenarios can result: If you have configured your service to allow exception details in faults, you will expose internals of your service opening up yourself for security breaches. Or you don't have this configured in your service and the consumer gets a very generic message that indicates something went wrong, which is not very useful for them or the support team.
What you should do is declare one or more FaultExceptions, depending on what messages you want the user to receive from your operation, decorate them as FaultContracts on your operation declaration. Then you can try...catch specific exceptions and throw specific Faults. You can also have a try...catch that catches exception and throw a very general Fault.
The key here, is not revealing too much information of what is going on with your operation internally - especially stack traces!
The fault is just another data contract, so it is declared in your WSDL. This means that your consumer can catch the fault specifically and can react to faults thrown from your operation as if it was an exception being thrown from their code.
Hope this helps.
Joe.
Yes, you should wrap Web service call in try-catch. DON'T use empty catch as they (mostly) are pure evil. Your catch block should at least log exception. I don't know about your applications logic, but probably some message (like "information from service wasn't fetched because of tech error") should be shown to user.
It's ok, but try to just catch exception types that you can handle.
Avoid catching any "Exception" or, if you do so, log and/or alert the user and/or retry to call the webservice.
If it's a windows forms app I usually wrap the last "Exception" catch in an #if DEBUG block to avoid hiding exceptions while debugging or testing.
#if !DEBUG
catch (Exception ex)
{
// show messagebox, log, etc
}
#endif
this is a case that could result in an exception being thrown, so yes it should be wrapped on a try catch block.
What to do with the exception handler it depends on the program logic...
Putting a web service method in a try catch block is a good idea,as you stated you do not want to crash the calling application because something went wrong in the web service method.
Additionally, rather than throw an exception back to the client, who can't do anything about it anyway, you may consider having all of your web service methods return a structure or small class that can contain the status of the call, an error code and an friendly message that could explain the error.
using System;
using System.ServiceModel;
using Entities; //my entities
using AuthenticationService; //my webservice reference
namespace Application.SL.Model
{
public class AuthenticationServiceHelper
{
/// <summary>
/// User log in
/// </summary>
/// <param name="callback"></param>
public void UserLogIn(Action<C48PR01IzhodOut, Exception> callback)
{
var proxy = new AuthenticationServiceClient();
try
{
proxy.UserLogInCompleted += (sender, eventargs) =>
{
var userCallback = eventargs.UserState as Action<C48PR01IzhodOut, Exception>;
if (userCallback == null)
return;
if (eventargs.Error != null)
{
userCallback(null, eventargs.Error);
return;
}
userCallback(eventargs.Result, null);
};
proxy.UserLogInAsync(callback);
}
catch (Exception ex)
{
proxy.Abort();
ErrorHelper.WriteErrorLog(ex.ToString());
}
finally
{
if (proxy.State != CommunicationState.Closed)
{
proxy.CloseAsync();
}
}
}
}
Is this a good practice or is there room for improvement?

Resources