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

Handle an exception in another method without losing the request objects from original one

当在数据库中找不到用户时会抛出异常,我想从控制器透视层处理该特定异常在@ExceptionHandler 注释 的分离方法中,不会丢失用户发送的原始数据。那么,所以,我正在使用 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 行: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();
        }
   }

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

注入

您可以查看文档 here 以了解在调用处理程序时 Spring 可以注入哪些参数。