51727

Spring Boot Custom Error Controller Returning empty json response

Question:

I got a spring boot app. I have configured a custom error controller to handle 404 errors. It is returning an empty response. I got log statements which shows that the custom error controller method is called. But I don't see a response in my SOAP UI or Chrome Postman. Please Help!!

@RestController public class MyErrorController implements ErrorController { private static final String PATH = "/error"; private boolean debug = true; private static final Logger log = LoggerFactory.getLogger(MyErrorController.class); @Autowired private ErrorAttributes errorAttributes; @RequestMapping(value = PATH) public MyGlobalError error(HttpServletRequest request, HttpServletResponse response) { log.error("***" + RequestCorrelation.getId() + "***" + "MyErrorController - error ()"); MyGlobalError error = new MyGlobalError(request.getMethod(), response.getStatus(), getErrorAttributes(request, debug)); return error; } @Override public String getErrorPath() { return PATH; } private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { RequestAttributes requestAttributes = new ServletRequestAttributes(request); return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace); } }

Here is my app class

@EnableAutoConfiguration // Sprint Boot Auto Configuration @ComponentScan(basePackages = "com.app") @EnableJpaRepositories("com.app.jpa") // To segregate MongoDB // and JPA repositories. // Otherwise not needed. @EnableSwagger // auto generation of API docs @SpringBootApplication @EnableAspectJAutoProxy @EnableConfigurationProperties public class Application extends SpringBootServletInitializer { private static Class<Application> appClass = Application.class; @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(appClass).properties(getProperties()); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public FilterRegistrationBean correlationHeaderFilter() { FilterRegistrationBean filterRegBean = new FilterRegistrationBean(); filterRegBean.setFilter(new CorrelationHeaderFilter()); filterRegBean.setUrlPatterns(Arrays.asList("/*")); return filterRegBean; } @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource dataSource() { return DataSourceBuilder.create().build(); } static Properties getProperties() { Properties props = new Properties(); props.put("spring.config.location", "classpath:/"); return props; } @Bean public WebMvcConfigurerAdapter webMvcConfigurerAdapter() { WebMvcConfigurerAdapter webMvcConfigurerAdapter = new WebMvcConfigurerAdapter() { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false).favorParameter(true).parameterName("media-type") .ignoreAcceptHeader(true).useJaf(false).defaultContentType(MediaType.APPLICATION_JSON) .mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON); } }; return webMvcConfigurerAdapter; } @Bean public RequestMappingHandlerMapping defaultAnnotationHandlerMapping() { RequestMappingHandlerMapping bean = new RequestMappingHandlerMapping(); bean.setUseSuffixPatternMatch(false); return bean; } }

And I have this in my properties file

error configurations

error.whitelabel.enabled=false

And here is my log entry

2016-05-04 12:26:45 - ***f37dbfea-daeb-4d35-bac3-73bb5fb25c1c***-Entering: MyErrorController.error 2016-05-04 12:26:45 - ***f37dbfea-daeb-4d35-bac3-73bb5fb25c1c***MyErrorController - error () 2016-05-04 12:26:45 - ***f37dbfea-daeb-4d35-bac3-73bb5fb25c1c***-Exited: MyErrorController.error

Answer1:

you can use a controller advice and a separate rest error handler and handle each exception type.<br /><a href="https://stackoverflow.com/a/33003627/839979" rel="nofollow">see this answer</a>

you can create a custom response json object the @ResponseBody annotation is needed here <br /> or a generic error response like the one used here <a href="https://stackoverflow.com/a/28903217/839979" rel="nofollow">click here</a>

Recommend

  • ModelDriven stopped working in Struts2
  • Pages restricted by login filter are still accessible by other users
  • Change request URL to point to different web server in servlet filter
  • Identifying path of current JSF / XHTML page [duplicate]
  • How to get ip adress and port in web service
  • Tomcat not applying filter after redirection (forwarding?)
  • How to redirect a logged out user to the home page in Java EE/JSF?
  • how to get Task id,Feature id,Complete hrs by accessing TFS Warehouse by date in VS 2017?
  • Using JIRA Query Language from Klipfolio To Query JIRA API For Number of Rejected Issues
  • ServletRequest get name of actual page
  • How would I obtain SessionFactory from the ServletContext in the DAO
  • Iterating through CSV and creating an XML file
  • TFS Scrum Burndown showing ideal line finishing above zero
  • Problems with Angular, CORS and Spring
  • Cannot call sendRedirect() after the response has been committed [duplicate]
  • Cannot get Servlet to process request content as UTF-8
  • Sometimes my set comes out ordered and sometimes not (Python)
  • JSF ServletFilter Restriction on index page when logged in
  • Perl: Inserting an XML::Twig node with XML::Twig
  • x64 applications using gdi+: what are the consequences on performance?
  • How to make a tree having multiple type of nodes and each node can have multiple child nodes in java
  • How to add a column to a Pandas dataframe made of arrays of the n-preceding values of another column
  • script to move all files from one location to another location
  • Akka Routing: Reply's send to router ends up as dead letters
  • AT Commands to Send SMS not working in Windows 8.1
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Trying to get generic when generic is not available
  • How do I configure my settings file to work with unit tests?
  • embed rChart in Markdown
  • How to get Windows thread pool to call class member function?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Is it possible to post an object from jquery to bottle.py?
  • Running Map reduces the dimensions of the matrices
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS
  • Android Heatmap on canvas or ImageView
  • Conditional In-Line CSS for IE and Others?
  • java string with new operator and a literal