spring mvc #ExceptionHandler method get same view - java

My problem is that I want to create an #ExceptionHandler method that will capture all un-handled exceptions. Once captured I would like to redirect to the current page instead of specifying a separate page just to display error.
Basically how do I get the value of someview returned by somemethod and set it dynamically in the method unhandledExceptionHandler below.
#ExceptionHandler(Exception.class)
protected ModelAndView unhandledExceptionHandler(Exception ex){
System.out.println("unhandle exception here!!!");
ModelAndView mv = new ModelAndView();
mv.setViewName("currentview");
mv.addObject("UNHANDLED_ERROR", "UNHANDLED ERROR. PLEASE CONTACT SUPPORT. "+ex.getMessage());
return mv;
}
#RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(HttpSession session) throws Exception {
String abc = null;
abc.length();
return "someview";
}
So in JSP I can render this error message back into the current page something like that.
<c:if test="${not empty UNHANDLED_ERROR}">
<div class="messageError"> ${UNHANDLED_ERROR}</div>
</c:if>

I don't think there is way to do what you are asking for, because in the exception handler method unhandledExceptionHandler there is no way to find out what the name of the view that the handler method somemethod would have returned.
The only way is for you to introduce some sort of meta data scheme so that when you end up in the exception handler you can figure out what view to map it to. But I think this meta data scheme would be fairly complex. You can implement such a scheme by finding out what was the original url being accessed when the exception was thrown, this can be done with the code snippet below.
(ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
Once you know what the original request URL you can redirect to it, maybe using flash attribute to store the fact that there was an exception and what the error is.
The main problem wit the metadata will occur when you have a handler method that select between different views something like.
#RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(HttpSession session) throws Exception {
String abc = null;
if(someCondition) {
abc.length();
return "someview";
} else {
// do some stuff here.
return "someOtherView";
}
}
Even knowing that somemethod was the source of the error leaves you not knowing which branch in the if statement caused the exception.

I dont think you can do this without modifying all of your handler methods. However you can try to do this in a "pretty" way:
1) You can define your own annotation which will accept target view name as a parameter (e.g. #ExceptionView)
2) Next thing to do is marking your handler methods with it, e.g.:
#ExceptionView("someview")
#RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(HttpSession session) throws Exception {
String abc = null;
abc.length();
return "someview";
}
3) After that you can do something like this in exception handler:
#ExceptionHandler(Exception.class)
protected ModelAndView unhandledExceptionHandler(Exception ex, HandlerMethod hm) {
String targetView;
if (hm != null && hm.hasMethodAnnotation(ExceptionView.class)) {
targetView = hm.getMethodAnnotation(ExceptionView.class).getValue();
} else {
targetView = "someRedirectView"; // kind of a fallback
}
ModelAndView mv = new ModelAndView();
mv.setViewName(targetView);
mv.addObject("UNHANDLED_ERROR", "UNHANDLED ERROR. PLEASE CONTACT SUPPORT. "+ex.getMessage());
return mv;
}

Rather than sending the error on a separate page, you can you just put the error in the ModelAndView object. In your case you can just put the try/catch in your controller method and return the same view like so:
#RequestMapping(value = "/somepage", method = RequestMethod.GET)
public String somemethod(ModelAndView mv,HttpSession session) throws Exception {
mv.setViewName("someview");
try{
String abc = null;
abc.length();
} catch(Exception e) {
mv.addObject("UNHANDLED_ERROR", "UNHANDLED ERROR. PLEASE CONTACT SUPPORT. "+ex.getMessage());
}
return mv;
}
So add the ModelAndView to your method and return it.

I have not tried this out, but based on the documentation here, we can get the request object in the exception handler. We may not be able to get the view linked to the URL. Getting the view from the URL, and the state/model of the view will be the tricky part.
#ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception ex) {
logger.error("Request: " + req.getRequestURL() + " raised " + ex);
ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}

Create a controller method annotated with #RequestMethod("/server-error")
Create a controller method annotated with #ExceptionHandler which will return "forward:/server-error";

Related

Handle an exception in another method without losing the request objects from original one

There is an Exception that is thrown when an user is not found in database and i'd like to handle that particular exception from the controller perspective layer in a separated method by #ExceptionHandler annotation without losing the original data sent by the user. Well, so, i'm using Sessions and my first attempt was trying to get the object back from it by HttpServletRequest but i got:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'pontoEditar' available as request attribute
The code:
#ExceptionHandler(ConversionFailException.class)
public String handleConversionFailException(HttpServletRequest request, RedirectAttributes attr) {
PontoEditarDTO ponto = (PontoEditarDTO) request.getAttribute("pontoEditar");
// I'd like to get the original object back ...
return "pontos/editar";
}
How would it be if i use a try-catch block
#PostMapping
public String editar(#ModelAttribute("pontoEditar") PontoEditarDTO ponto, HttpSession session) {
// ... simplified.
Ponto pontoConvertido = null;
try {
pontoConvertido = pontoConverter.convert(ponto);
catch (ConversionFailException ex) {
attr.addFlashAttribute("error", "User not found!");
return "redirect:/ponto/listar";
}
// ...
return "redirect:/ponto/listar";
}
Here the simplified code:
public class ConversionFailException extends RuntimeException {
public ConversionFailException(String mensagem) {
super(mensagem);
}
}
Controller with POST.
The exception happens in the POST at line with: Ponto pontoConvertido = pontoConverter.convert(ponto);
#Controller
#SessionAttributes("pontoEditar")
#RequestMapping("/ponto/editar")
public class PontoEditarController {
// ... GET Removed.
#PostMapping
public String editar(#ModelAttribute("pontoEditar") PontoEditarDTO ponto, HttpSession session) {
// ... simplified.
Ponto pontoConvertido = pontoConverter.convert(ponto);
// ...
return "redirect:/ponto/listar";
}
#ExceptionHandler(ConversionFailException.class)
public String handleConversionFailException(HttpServletRequest request, RedirectAttributes attr) {
attr.addFlashAttribute("falha", "Usuário não foi encontrado");
/* I tried but it failed, how can i get ? */
PontoEditarDTO ponto = (PontoEditarDTO) request.getAttribute("pontoEditar");
return "pontos/editar";
}
#GetMapping("pontoEditar")
public PontoEditarDTO getPontoModel() {
return new PontoEditarDTO();
}
}
You can add WebRequest (or HttpSession, etc...) as a parameter in your exception handler, it will be injected by Spring.
You can have a look at the documentation here to see what parameter can be injected by Spring when the handler is called.

Redirect ModelAndView with message

My application has a method to update a conference. After doing so I have a modelandview with a redirect to the main conference list. This all works fine although the message which I add as an object to the modelandview does not display.
My method in my controller:
#PostMapping("/updateConference")
public ModelAndView updateConference(
#ModelAttribute("conference") #Valid ConferenceDto conferenceDto, BindingResult result) {
if(result.hasErrors()){
return new ModelAndView("updateConference","conferenceDto", conferenceDto);
}
try {
conferenceService.updateConference(conferenceDto);
} catch (ConferenceAlreadyExistException uaeEx) {
ModelAndView mav = new ModelAndView("updateConference","conferenceDto", conferenceDto);
mav.addObject("message", uaeEx.getMessage());
return mav;
}
ModelAndView mav = new ModelAndView("redirect:/teacher/configure"); // Problem is here
mav.addObject("message", "Successfully modified conference.");
return mav;
}
In my html I have the line:
<div th:if="${message != null}" th:align="center" class="alert alert-info" th:utext="${message}">message</div>
After updating the conference it goes back to configure.html although the message does not show. In the url I can see http://localhost:8080/teacher/configure?message=Successfully+modified+conference
I have looked at this thread although it did not help.
I tried to experiment by setting ModelAndView mav = new ModelAndView("configure") and the message displays but my conference list is empty and the url is http://localhost:8080/teacher/updateconference
Any tips is highly appreciated!
EDIT
I have tried to use RedirectAttributes as crizzis pointed out & this page and have this now:
#PostMapping("/updateConference")
public String updateConference(
#ModelAttribute("conference") #Valid ConferenceDto conferenceDto, BindingResult result, RedirectAttributes attributes) {
if(result.hasErrors()){
attributes.addFlashAttribute("org.springframework.validation.BindingResult.conferenceDto", result);
attributes.addFlashAttribute("conferenceDto", conferenceDto);
return "redirect:/teacher/updateConference";
}
try {
conferenceService.updateConference(conferenceDto);
} catch (ConferenceAlreadyExistException uaeEx) {
attributes.addFlashAttribute("conferenceDto", conferenceDto);
attributes.addFlashAttribute("message", uaeEx.getMessage());
return "redirect:/teacher/updateConference";
}
attributes.addFlashAttribute("message", "Successfully modified conference.");
return "redirect:/teacher/configure";
}
My get method:
#GetMapping(path = "/updateConference/{id}")
public String showUpdateConferenceForm(#PathVariable(name = "id") Long id, Model model){
Optional<Conference> conference = conferenceService.findById(id);
if (!model.containsAttribute("ConferenceDto")) {
model.addAttribute("conference", new ConferenceDto());
}
return "updateConference";
}
This works as intended and my message is shown on my configure.html . However, when I have an error in BindingResults the application goes to an error page and I get this in the console:
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported]
Use RedirectAttributes which has addFlashAttribute method. You can set the success or failure message like you did and access that message through the key in the redirected page as you need.
when the error occurs you are redirecting to the same method instead of this you can just render the template in case there is error. I do this way.

Spring - Construct new modelAndView from existing BindingResult and Model

I am trying to improve my Spring MVC application to use a global exception handler to catch various persistence exceptions across all my controllers. This is the controller code that runs when the user tries to save a new StrengthUnit object for example. All the validations work perfectly fine and the form is correctly returned with an error message underneath the name field when the PersistenceException is thrown. The resulting page also correctly contains the strengthUnit attribute and is able to bind the field (this entity just has a name field) back to the form :
#RequestMapping(value = {"/newStrengthUnit"}, method = RequestMethod.POST)
public String saveStrengthUnit(#Valid StrengthUnit strengthUnit, BindingResult result, ModelMap model) throws Exception
{
try
{
setPermissions(model);
if (result.hasErrors())
{
return "strengthUnitDataAccess";
}
strengthUnitService.save(strengthUnit);
session.setAttribute("successMessage", "Successfully added strength unit \"" + strengthUnit.getName() + "\"!");
}
catch (PersistenceException ex)
{
FieldError error = new FieldError("strengthUnit", "name", strengthUnit.getName(), false, null, null,
"Strength unit \"" + strengthUnit.getName() + "\" already exists!");
result.addError(error);
return "strengthUnitDataAccess";
}
return "redirect:/strengthUnits/list";
}
I am trying to use this as a starting point to incorporate the global exception handler that i built and I don't understand how that handler can be called and return the same page with the same model and binding result. I have tried something extremely ugly with a custom exception just to try and understand the mechanics and get the handler to return me the same page as before and I'm unable to get it to work.
Here is the custom exception I built :
public class EntityAlreadyPersistedException extends Exception
{
private final Object entity;
private final FieldError error;
private final String returnView;
private final ModelMap model;
private final BindingResult result;
public EntityAlreadyPersistedException(String message, Object entity, FieldError error, String returnView, ModelMap model, BindingResult result)
{
super(message);
this.entity = entity;
this.error = error;
this.returnView = returnView;
this.model = model;
this.result = result;
}
public Object getEntity()
{
return entity;
}
public FieldError getError()
{
return error;
}
public String getReturnView()
{
return returnView;
}
public ModelMap getModel()
{
return model;
}
public BindingResult getResult()
{
return result;
}
}
Here is my modified catch block in my controller's saveStrengthUnit method :
catch (PersistenceException ex)
{
FieldError error = new FieldError("strengthUnit", "name", strengthUnit.getName(), false, null, null,
"Strength unit \"" + strengthUnit.getName() + "\" already exists!");
result.addError(error);
throw new EntityAlreadyPersistedException("Strength unit \"" + strengthUnit.getName() + "\" already exists!", strengthUnit, error,
"strengthUnitDataAccess", model, result);
}
And finally the global exception handler's method to catch it :
#ExceptionHandler(EntityAlreadyPersistedException.class)
public ModelAndView handleDataIntegrityViolationException(HttpServletRequest request, Exception ex)
{
EntityAlreadyPersistedException actualException;
actualException = ((EntityAlreadyPersistedException)ex);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName(actualException.getReturnView());
modelAndView.addObject(BindingResult.MODEL_KEY_PREFIX + "strengthUnitForm", actualException.getResult());
if (actualException.getEntity() instanceof StrengthUnit)
{
modelAndView.addObject("strengthUnit", (StrengthUnit)actualException.getEntity());
}
return modelAndView;
}
This is extremely ugly and probably very foolish to an experienced Spring developer but I am not quite one (yet). This works BUT the binding result is lost and the validation errors do not appear. How can I modify this code to behave as it was before while still using the global exception handler to handle all errors?
Thanks!
If you are trying to catch the valid exception , which was throw when you are using the #Valid .And you want same handler handle that exception ,then add one more exception class in the #ExceptionHandler annotation
What the doc says
The #ExceptionHandler value can be set to an array of Exception
types. If an exception is thrown matches one of the types in the list,
then the method annotated with the matching #ExceptionHandler will be
invoked. If the annotation value is not set then the exception types
listed as method arguments are used.
The exception thrown by the #Valid annotation is MethodArgumentNotValidException , So you can add this exception on same handler method
I hope this may help you
1.you are setting the entity as strengthUnit.getName() not strengthUnit
throw new EntityAlreadyPersistedException("Strength unit \"" + strengthUnit.getName() + "\" already exists!", strengthUnit, error,
"strengthUnitDataAccess", model, result);
2.but you are checking if (actualException.getEntity() instanceof StrengthUnit
Hope it helps, Try to set the entity as strengthUnit.

spring HandlerExceptionResolver write json object to httpservletresponse

I am handling negative cases like calling GET API which is actually a POST call. This gives Method Not Found Error with 405 status by Spring.
But I want my own exception so I added the following resolver:
public class HandlerExceptionResolver
implements org.springframework.web.servlet.HandlerExceptionResolver {
protected final Log logger = LogFactory.getLog(this.getClass());
#Override
public ModelAndView resolveException(
HttpServletRequest request, HttpServletResponse response,
Object handler,Exception exception) {
logger.trace("-------------doResolveException-------------");
System.out.println("-------------doResolveException-------------");
if(exception instanceof HttpRequestMethodNotSupportedException) {
Fault fault = new Fault();
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
String errorMessage;
try {
errorMessage = mapper.writeValueAsString(fault);
response.setStatus(405);
response.setContentType("application/json");
response.getWriter().println(errorMessage);
response.getWriter().flush();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
But this doesn't writes the JSON to response.
I don't think you're supposed to want to write your own output using that response parameter. Spring expects your method to return a ModelAndView instance, which you can populate with the data you want to send to the user (the model part) and the name of the view resource that will be used to render it. You would then also need to define a new view resource that will just generate the JSON you want, out of the data in the ModelAndView...
As for concern can you debug out the value of
errorMessage = mapper.writeValueAsString(fault);
there is better way to do this exception handling.
#ExceptionHandler(HandlerExceptionResolver.class)
public ModelAndView handleEmployeeNotFoundException(HttpServletRequest request, Exception ex){
logger.error("Requested URL="+request.getRequestURL());
logger.error("Exception Raised="+ex);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", ex);
modelAndView.addObject("url", request.getRequestURL());
modelAndView.setViewName("error");
return modelAndView;
}
You can try also if you want to use #ExceptionHandler to handle this
situation.

Spring MVC : the best way to handle exception for Ajax Request and normal request?

I want to define a common exception manger in my project, so I use #ControllerAdvice to do, the snippet of code is below:
#ExceptionHandler(Exception.class)
public ModelAndView handleAllException(HttpServletRequest request, Exception ex) throws Exception
{
LOGGER.error(ex.getMessage());
ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", request.getRequestURL());
mav.setViewName(ViewConstants.INTERNAL_ERROR_VIEW);
return mav;
}
it will return a common error page. That's great for normal exception of request. But if this is a Ajax request, the result is so ugly. so I add the code to judge it. The added code is below:
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
// return HTTP Status code and response message
} else {
// return error page name
}
I don't think it is the best way, anybody have a good opinion?
I have all my controllers in different packages based on whether they serve AJAX requests or not. Then I can set #basePackages element on the ControllerAdvice annotations to handle the exception accordingly
Update:
See RequestMapping#params and RequestMapping#headers to separate controllers based on headers and/or params
I would suggest to set error response code on any request, think this is a good practice to notify client that something goes wrong not depending on type of request. And for ajax request you can return same page and identify problem by error code.
If you use jQuery for making requests, you could use the following:
jQuery.ajaxSetup({
headers: { 'ajax-request': true },
statusCode: {
400: function (xhr) {
...do something
},
500: function (xhr) {
...do something
}
...
}
});
...
public class Application extends SpringBootServletInitializer {
#Bean(name = "simpleMappingExceptionResolver")
public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
r.setDefaultErrorView("forward:/errorController");
return r;
}
#Controller
public class ErrorController {
public static final Logger LOG = Logger.getLogger(ErrorController.class);
#RequestMapping(value = "/errorController")
public ModelAndView handleError(HttpServletRequest request,
#RequestAttribute("exception") Throwable th) {
ModelAndView mv = null;
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
if (isBusinessException(th)) {
mv = new ModelAndView("appAjaxBadRequest");
mv.setStatus(BAD_REQUEST);
} else {
LOG.error("Internal server error while processing AJAX call.", th);
mv = new ModelAndView("appAjaxInternalServerError");
mv.setStatus(INTERNAL_SERVER_ERROR);
}
mv.addObject("message", getUserFriendlyErrorMessage(th).replaceAll("\r?\n", "<br/>"));
} else {
LOG.error("Cannot process http request.", th);
mv = new ModelAndView("appErrorPage");
mv.addObject("exeption", th);
}
return mv;
}
}

Categories