在任何类型的异常情况下重定向到错误控制器?

时间:2018-07-24 09:34:13

标签: java spring spring-mvc spring-boot

我正在尝试创建一个Spring Boot应用程序。我创建了一个简单的演示方法来展示我的问题。

class OrderItem(models.Model):
    product = models.CharField(max_length=350)
    quantity = models.IntegerField()
    price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name='USD Price')
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items_in_this_order')
    date = models.DateField()
    time_from = models.TimeField()
    time_to = models.TimeField()
    made_by = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True, related_name='product_by')
    image = models.ImageField()
    order_date = models.DateField(auto_now_add=True)
    picked = models.ManyToManyField(User, blank=True, related_name='item_picked')

我在这里抛出@RequestMapping(value = "/customers", method = RequestMethod.GET) public List<Customer> getCustomers() { int i=0; if(i==0){ throw new RuntimeException("test exception"); } return (List<Customer>) jdbcCustomerDAO.findAll(); } 。我想将其重定向到我要在/ src / main / webapp中打开RuntimeException的地方。{p>

ErrorController

error.jsp

@Controller
public class MyCustomErrorController implements ErrorController{

    @Override
    public String getErrorPath() {
        return "/error";
    }

     @GetMapping("/error")
     public ModelAndView handleError(Model model) {
         model.addAttribute("message", "Oops Sorry !!!!");
         return new ModelAndView("error");             
     }
    }

我在页面上收到此错误:

Error.jsp file

如何将其重定向到我的错误pagE?

1 个答案:

答案 0 :(得分:1)

Why not capture the exceptions using Spring own feature regarding errors? You can use something called ControllerAdvice (documented here). So, in your case, you can do something similar to the following:

@ControllerAdvice
public class MyCustomErrorController {

 @ExceptionHandler(RuntimeException.class)
 public ModelAndView handleError(RuntimeException exception) {
     model.addAttribute("message", "Oops Sorry !!!!");
     return new ModelAndView("error");
 }

} 

It might be that you can use this type of error handling instead. Let me know if something does not work as intended. A small reference can also be found on Spring' own blog.

相关问题