简体   繁体   中英

Rest Api exception handling

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.

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;
 }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM