Ismael Ezequiel Ismael Ezequiel - 4 months ago 74
Java Question

How I create an error handler (404, 500...) in Spring boot/mvc?

For some hours I'm trying to create a CUSTOM global error handler in Spring Boot/MVC. I've read a lot of articles and nothing... :/ Please. Help me.

That is my error class:

`
I tried create a class like that

@Controller
public class ErrorPagesController {

@RequestMapping("/404")
@ResponseStatus(HttpStatus.NOT_FOUND)
public String notFound() {
return "/error/404";
}

@RequestMapping("/403")
@ResponseStatus(HttpStatus.FORBIDDEN)
public String forbidden() {
return "/error/403";
}

@RequestMapping("/500")
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String internalServerError() {
return "/error/500";
}


}

`
**** QUESTION SOLVED ****
I've used this way:

`

@Configuration
public class ErrorConfig implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404"));
}
}


`

Answer

Hope this will help: Create a class say: NoProductsFoundException that extends runtimexception.

    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.ResponseStatus;

    @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No products found under this category")
    public class NoProductsFoundException extends RuntimeException{

    private static final long serialVersionUID =3935230281455340039L;
    }

Then in your productcontroller:

    @RequestMapping("/{category}")
    public String getProductsByCategory(Model
    model,@PathVariable("category") String category) {

   List<Product> products = productService.getProductsByCategory(category);

   if (products == null || products.isEmpty()) {
   throw new NoProductsFoundException ();
   }
   model.addAttribute("products", products);
   return "products";
}

enter image description here