在另一种方法中处理异常,而不丢失原始方法中的请求对象

发布于 2025-01-16 03:51:26 字数 2642 浏览 0 评论 0原文

当在数据库中找不到用户时,会抛出一个异常,并且我想通过 @ExceptionHandler 注释在单独的方法中从控制器视角层处理该特定异常 em> 不会丢失用户发送的原始数据。嗯,所以,我正在使用 Sessions,我的第一次尝试是尝试通过 HttpServletRequest 从中取回对象,但我得到:

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'pontoEditar' available as request attribute

代码:

@ExceptionHandler(ConversionFailException.class)
public String handleConversionFailException(HttpServletRequest request, RedirectAttributes attr) {

    PontoEditarDTO ponto = (PontoEditarDTO) request.getAttribute("pontoEditar");
    // I'd like to get the original object back ...     

    return "pontos/editar";
}

如果我使用 try-catch 块会怎么样

@PostMapping
public String editar(@ModelAttribute("pontoEditar") PontoEditarDTO ponto, HttpSession session) {
    
    // ... simplified.
    Ponto pontoConvertido = null;
    try {
        pontoConvertido = pontoConverter.convert(ponto);
    catch (ConversionFailException ex) {
        attr.addFlashAttribute("error", "User not found!");
        return "redirect:/ponto/listar";
    }

    // ... 
    return "redirect:/ponto/listar";
}

这里是简化的代码:

public class ConversionFailException extends RuntimeException {
    public ConversionFailException(String mensagem) {
        super(mensagem);
    }
}
  • 带有 POST 的控制器。

异常发生在 POST 中:Ponto pontoConvertido = pontoConverter.convert(ponto);

    @Controller
    @SessionAttributes("pontoEditar")
    @RequestMapping("/ponto/editar")
    public class PontoEditarController {
        
        // ... GET Removed.

        @PostMapping
        public String editar(@ModelAttribute("pontoEditar") PontoEditarDTO ponto, HttpSession session) {
            
            // ... simplified.
            Ponto pontoConvertido = pontoConverter.convert(ponto);
            // ... 
            return "redirect:/ponto/listar";
        }
        
        @ExceptionHandler(ConversionFailException.class)
        public String handleConversionFailException(HttpServletRequest request, RedirectAttributes attr) {
            attr.addFlashAttribute("falha", "Usuário não foi encontrado");
            
            /* I tried but it failed, how can i get ? */
            PontoEditarDTO ponto = (PontoEditarDTO) request.getAttribute("pontoEditar");
            

            return "pontos/editar";
        }
        
        @GetMapping("pontoEditar")
        public PontoEditarDTO getPontoModel() {
            return new PontoEditarDTO();
        }
   }

There is an Exception that is thrown when an user is not found in database and i'd like to handle that particular exception from the controller perspective layer in a separated method by @ExceptionHandler annotation without losing the original data sent by the user. Well, so, i'm using Sessions and my first attempt was trying to get the object back from it by HttpServletRequest but i got:

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'pontoEditar' available as request attribute

The code:

@ExceptionHandler(ConversionFailException.class)
public String handleConversionFailException(HttpServletRequest request, RedirectAttributes attr) {

    PontoEditarDTO ponto = (PontoEditarDTO) request.getAttribute("pontoEditar");
    // I'd like to get the original object back ...     

    return "pontos/editar";
}

How would it be if i use a try-catch block

@PostMapping
public String editar(@ModelAttribute("pontoEditar") PontoEditarDTO ponto, HttpSession session) {
    
    // ... simplified.
    Ponto pontoConvertido = null;
    try {
        pontoConvertido = pontoConverter.convert(ponto);
    catch (ConversionFailException ex) {
        attr.addFlashAttribute("error", "User not found!");
        return "redirect:/ponto/listar";
    }

    // ... 
    return "redirect:/ponto/listar";
}

Here the simplified code:

public class ConversionFailException extends RuntimeException {
    public ConversionFailException(String mensagem) {
        super(mensagem);
    }
}
  • Controller with POST.

The exception happens in the POST at line with: Ponto pontoConvertido = pontoConverter.convert(ponto);

    @Controller
    @SessionAttributes("pontoEditar")
    @RequestMapping("/ponto/editar")
    public class PontoEditarController {
        
        // ... GET Removed.

        @PostMapping
        public String editar(@ModelAttribute("pontoEditar") PontoEditarDTO ponto, HttpSession session) {
            
            // ... simplified.
            Ponto pontoConvertido = pontoConverter.convert(ponto);
            // ... 
            return "redirect:/ponto/listar";
        }
        
        @ExceptionHandler(ConversionFailException.class)
        public String handleConversionFailException(HttpServletRequest request, RedirectAttributes attr) {
            attr.addFlashAttribute("falha", "Usuário não foi encontrado");
            
            /* I tried but it failed, how can i get ? */
            PontoEditarDTO ponto = (PontoEditarDTO) request.getAttribute("pontoEditar");
            

            return "pontos/editar";
        }
        
        @GetMapping("pontoEditar")
        public PontoEditarDTO getPontoModel() {
            return new PontoEditarDTO();
        }
   }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绿光 2025-01-23 03:51:26

您可以在异常处理程序中添加 WebRequest (或 HttpSession 等)作为参数,它将由 Spring 注入。

您可以查看文档 这里看看Spring在调用handler时可以注入什么参数。

You can add WebRequest (or HttpSession, etc...) as a parameter in your exception handler, it will be injected by Spring.

You can have a look at the documentation here to see what parameter can be injected by Spring when the handler is called.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文