How I create an error handler (404, 500…) in Spring Boot/MVC

后端 未结 5 1799
终归单人心
终归单人心 2020-12-05 06:06

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.

That is my error class:

5条回答
  •  旧巷少年郎
    2020-12-05 06:35

    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 products = productService.getProductsByCategory(category);
    
       if (products == null || products.isEmpty()) {
       throw new NoProductsFoundException ();
       }
       model.addAttribute("products", products);
       return "products";
    }
    

提交回复
热议问题