2017-03-01 32 views
1

我正在寻找一种方法来重定向到一个没有映射/直接请求的方法中的错误页面,但是通过一个方法调用它。重定向到非映射方法的错误页面

实施例:

//调用方法

@GetMapping("/") 
public String listUploadedFiles() {  
    doSomething(); // redirect if error must happen in side this method! 
    return "uploadForm"; 
} 

//方法,其中重定向应该发生

public void doSomething() 
{ 
    try { 
     // try some code here 
    } catch(Exception e) { 
     // call a method which redirects to an error page 
    } 
} 

上述方法,由具有一个映射,我想的方法称为在发生异常的方法中直接重定向到错误。这可能与春季启动?

回答

1

您可以使用@ExceptionHandler

@GetMapping("/") 
public String listUploadedFiles() {  
    doSomething(); // redirect if error must happen in side this method! 
    return "uploadForm"; 
} 


public void doSomething() { 
    try { 
     // try some code here 
    } catch(Exception e) { 
     throw new YourException(); 
    } 
} 

@ExceptionHandler(YourException.class) 
public String handleYourException(YourException e) { 
    return "errorPage"; 
} 
+1

这只会工作,这个类。但是如果你想使'@ ExceptionHandler''适用于多个控制器类,只需创建类并用''@ ControllerAdvice'''注释它,然后用''ExceptionHandler'''放入方法这个答案。 – Optio

+0

谢谢!完美工作 – DazstaV3