0

I am having different projects for Service and Web. I would like to know how to handle when specific exception comes from Services. For example I am handling DuplicateDataException as follows at Service side:

public void serviceFunction()
{
try
{
//code
}catch(DuplicateDataException e)
{
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                    .entity(e.getMessage()).build();
}}

At UI side: controller class is calling the service function through Rest API

@RequestMapping(value = "/addNew", method = RequestMethod.POST)
    public ModelAndView addNew(Object obj) { 

try {
            restTemplate.exchange(url, HttpMethod.POST, httpEntity,
                    Object.class);
             LOGGER.info("Object Created Successfully");
        } catch (Exception e) { 
return ModelAndView("PageName", "param","value");
}
}

At UI side I am getting Internal Server Error, Instead I would like to get the entity error message value which was set at service side.

anju888
  • 23
  • 8
  • Why are you sending a 5xx class message for something that's more likely a 4xx class error? – Makoto Dec 22 '17 at 20:19
  • I tried with BAD_REQUEST also but it is going to the same catch block where for return ModelAndView("PageName", "param","value"); I need "value" as the message set in entity of return response at Service side . – anju888 Dec 22 '17 at 20:25
  • Possible dupe: https://stackoverflow.com/q/35323174/1079354 – Makoto Dec 22 '17 at 20:27

1 Answers1

0

As a kind of best practice try to catch your exceptions in your service code and throw an RuntimeException("An error occured") or a self defined Exception which extends Java's RuntimeException. Then you can define a global ExceptionHandler for all of your controllers and return your own error page like:

@ControllerAdvice
public class MyExceptionHandler {

  @ResponseStatus(HttpStatus.NOT_FOUND)
  @ExceptionHandler(Exeption.class)
  public ModelAndView handleFileNotFoundException(Exception exception){

    ModelAndView modelAndView = new ModelAndView();

    modelAndView.setViewName("yourView");
    modelAndView.addObject("exception", exception);

    return modelAndView;
 }

}
rieckpil
  • 10,470
  • 3
  • 32
  • 56