Ismael Ezequiel Ismael Ezequiel - 1 year ago 206
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

public class ErrorPagesController {

public String notFound() {
return "/error/404";

public String forbidden() {
return "/error/403";

public String internalServerError() {
return "/error/500";


I've used this way:


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


Answer Source

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:

    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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download