1
votes

I have implemented a RestControllerAdvice for handling exception in Spring Boot-Tomcat Web application as shown below :

@RestControllerAdvice 
public class ExceptionHandlerRest{
 private Logger logger=LoggerFactory.getLogger(getClass());

 @ExceptionHandler(Exception.class)
 public ResponseEntity<?> handleException(Exception ex){
  logger.error("System Error", ex);
  SimpleResponse=new SimpleResponse(ex.getMessage(),"Error code 001"));
  return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
 }

}

So whenever a web request results into exception i am expecting above handler to return status 500 and a json having content : "{"technicalMessage" : "NullPointerException","userMessage":"Error Code 001"}

However,instead of that a html error page is coming printing entire stack trace as shown below :enter image description here

the SimpleResponse has below definition :

public class SimpleResponse{
   String technicalMessage,userMessage;

   //public getters and setters


}

I have put debug point and observed that code flow does reach properly to return statement of handleException of RestControllerAdvice. I think some how tomcat is ignoring my response and showing exception stack trace. How can i make my application return error message in a json ?

1
Yes i am sure . I debugged and control is coming to exception handler and properly returning POJO response but some how tomcat is ignoring it and showing default error page - Goro
Is this on an embedded Tomcat or on an external one? (PS. I noticed your last paragraph that's why I deleted my original comment. ) - g00glen00b
yes embedded tomcat - Goro
I can't reproduce this with the code you provided, so I guess the error is elsewhere. What is BaseScreeningException? Is this being thrown within your exception handler? - g00glen00b
It is being thrown by rest controller when it sees some bad request - Goro

1 Answers

2
votes

I could resolve the issue. This issue was happening for rest controller which annotated with @RequestMapping(produces=MediaType.application_pdf_value). Some how when error was throw and was received by error handler, the POJO was not getting converted to JSON due to produces attribute of actual controller. I removed the produces attribute and instead set content type explicitly into response. Now both scenarios are working fine, downloading of pdf or exception message display.