gpt4 book ai didi

java - 如何重定向到我的 try catch 中的错误 View ?

转载 作者:行者123 更新时间:2023-12-02 09:17:43 26 4
gpt4 key购买 nike

我在 try catch 中返回了错误 View 当我的方法重新运行 ModelAnd View 时它工作得很好,但是当我的方法有一个 String 返回时我如何返回我的 View ?

像这样

   @RequestMapping(value="/librairie/supprimerLivre/{isbn}", method = RequestMethod.GET)
public String supprimerLivre(@PathVariable("isbn") String isbn, HttpServletRequest request){
try{
gestPanier = new GestPanier(request);
//rechercher le livre qui correspond a l'isbn passer en parametre
LivreAchete livre = gestPanier.getListe().stream().filter(c -> c.getIsbn().equals(isbn)).findFirst().get();

//supprimer le livre
gestPanier.supprimer(livre);
return "redirect:/librairie/afficherPanier";
}
catch(Exception ex){
return ModelAndView return new ModelAndView("Error", "model",new ErrorviewModel("/librairie/paiement", ex.getMessage(), ex));
}
}

我无法返回 ModelAndView,因为我的方法有一个字符串返回,但我如何重定向到我的 View ?

最佳答案

你可以尝试这样的事情(这是基于 Controller 的异常处理的 Spring 方式之一):

    // Name of the function is not important (just an example)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(RuntimeException.class) // Or handle some custom exception of yours
public ModelAndView supprimerLivreHandler(HttpServletRequest request, Exception ex) {
return new ModelAndView("Error", "model",new ErrorviewModel("/librairie/paiement", ex.getMessage(), ex));
}

@RequestMapping(value="/librairie/supprimerLivre/{isbn}", method = RequestMethod.GET)
public String supprimerLivre(@PathVariable("isbn") String isbn, HttpServletRequest request){
try{
gestPanier = new GestPanier(request);
//rechercher le livre qui correspond a l'isbn passer en parametre
LivreAchete livre = gestPanier.getListe().stream().filter(c -> c.getIsbn().equals(isbn)).findFirst().get();

//supprimer le livre
gestPanier.supprimer(livre);
return "redirect:/librairie/afficherPanier";
}
catch(Exception ex){
// When this Exception is thrown, the supprimerLivreHandler function will be called
throw new RuntimeException(); // Or throw some custom exception of yours
}
}

如果您想了解更多有关Spring MVC异常处理的信息,请参阅this website (我的示例基于该网站上描述的方法之一)。

关于java - 如何重定向到我的 try catch 中的错误 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58881920/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com